buildrom v3.24.0, rombuild v2.17.3, rofsbuild v2.10.4, resource compiler v8.4.001, image check v1.4.0, elftools v2.3, elf2e32 v2.3
authorjjkang
Wed, 23 Jun 2010 16:56:47 +0800
changeset 590 360bd6b35136
parent 588 c7c26511138f
child 591 22486c9c7b15
buildrom v3.24.0, rombuild v2.17.3, rofsbuild v2.10.4, resource compiler v8.4.001, image check v1.4.0, elftools v2.3, elf2e32 v2.3
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/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
buildframework/helium/build.xml
buildframework/helium/hlm.bat
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/h_utl.h
e32tools/elf2e32/source/imgdump.cpp
e32tools/elf2e32/source/pagedcompress.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/imaker/buildrom_plugins/group/bld.inf
imgtools/imaker/buildrom_plugins/hide.pm
imgtools/imaker/buildrom_plugins/localise.pm
imgtools/imaker/buildrom_plugins/localise_all_resources.pm
imgtools/imaker/buildrom_plugins/obyparse.pm
imgtools/imaker/buildrom_plugins/override.pm
imgtools/imaker/buildrom_plugins/plugincommon.pm
imgtools/imaker/config/example_image_conf_buildinfo.mk
imgtools/imaker/config/example_image_conf_naming.mk
imgtools/imaker/config/example_image_conf_platform.mk
imgtools/imaker/config/example_image_conf_product.mk
imgtools/imaker/config/example_imaker_extension.mk
imgtools/imaker/config/example_language_variant.mk
imgtools/imaker/config/example_system_languages.mk
imgtools/imaker/config/group/bld.inf
imgtools/imaker/group/bld.inf
imgtools/imaker/src/imaker.cmd
imgtools/imaker/src/imaker.mk
imgtools/imaker/src/imaker.pl
imgtools/imaker/src/imaker.pm
imgtools/imaker/src/imaker_core.mk
imgtools/imaker/src/imaker_help.mk
imgtools/imaker/src/imaker_image.mk
imgtools/imaker/src/imaker_minienv.mk
imgtools/imaker/src/imaker_odp.mk
imgtools/imaker/src/imaker_public.mk
imgtools/imaker/src/imaker_rofs2.mk
imgtools/imaker/src/imaker_rofs3.mk
imgtools/imaker/src/imaker_rofs4.mk
imgtools/imaker/src/imaker_tools.mk
imgtools/imaker/src/imaker_uda.mk
imgtools/imaker/src/imaker_variant.mk
imgtools/imaker/src/imaker_version.mk
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/filesystem/include/cluster.h
imgtools/imglib/filesystem/include/directory.h
imgtools/imglib/filesystem/include/dirregion.h
imgtools/imglib/filesystem/include/errorhandler.h
imgtools/imglib/filesystem/include/fatbasebootsector.h
imgtools/imglib/filesystem/include/filesysteminterface.h
imgtools/imglib/filesystem/include/longentry.h
imgtools/imglib/filesystem/include/longname.h
imgtools/imglib/filesystem/include/messageimplementation.h
imgtools/imglib/filesystem/include/utils.h
imgtools/imglib/filesystem/source/cluster.cpp
imgtools/imglib/filesystem/source/directory.cpp
imgtools/imglib/filesystem/source/dirregion.cpp
imgtools/imglib/filesystem/source/errorhandler.cpp
imgtools/imglib/filesystem/source/fat16filesystem.cpp
imgtools/imglib/filesystem/source/fat32filesystem.cpp
imgtools/imglib/filesystem/source/fatbasebootsector.cpp
imgtools/imglib/filesystem/source/filesysteminterface.cpp
imgtools/imglib/filesystem/source/longentry.cpp
imgtools/imglib/filesystem/source/longname.cpp
imgtools/imglib/filesystem/source/messageimplementation.cpp
imgtools/imglib/group/bld.inf
imgtools/imglib/group/filesystem.mmp
imgtools/imglib/group/imglib.mrp
imgtools/imglib/host/h_file.cpp
imgtools/imglib/host/h_utl.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
sbsv2/raptor/bin/buildstats.py
sbsv2/raptor/bin/codetest_osbuild.sh
sbsv2/raptor/bin/countbinaries.sh
sbsv2/raptor/bin/createrfifile.pl
sbsv2/raptor/bin/createvmap.py
sbsv2/raptor/bin/failedstats.py
sbsv2/raptor/bin/fixmeta.py
sbsv2/raptor/bin/install_raptor.sh
sbsv2/raptor/bin/mkgetfailed.py
sbsv2/raptor/bin/oby2linux.py
sbsv2/raptor/bin/osbuild.sh
sbsv2/raptor/bin/raptorlog.py
sbsv2/raptor/bin/readme.txt
sbsv2/raptor/bin/sbs
sbsv2/raptor/bin/sbs.bat
sbsv2/raptor/bin/sbsv2cache.py
sbsv2/raptor/bin/setup_user.sh
sbsv2/raptor/bin/speedtest_osbuild.sh
sbsv2/raptor/bin/squashlog.py
sbsv2/raptor/bin/statcollate.py
sbsv2/raptor/bin/unsplitdirs.py
sbsv2/raptor/bin/vartoxml.py
sbsv2/raptor/bin/whatsource.py
sbsv2/raptor/examples/os_properties.xml
sbsv2/raptor/examples/sbs_init.xml
sbsv2/raptor/lib/config/arm.xml
sbsv2/raptor/lib/config/build.xml
sbsv2/raptor/lib/config/carbide.xml
sbsv2/raptor/lib/config/coverity.xml
sbsv2/raptor/lib/config/default.xml
sbsv2/raptor/lib/config/gcc.xml
sbsv2/raptor/lib/config/gcce.xml
sbsv2/raptor/lib/config/gccxml.xml
sbsv2/raptor/lib/config/interfaces.xml
sbsv2/raptor/lib/config/locations.xml
sbsv2/raptor/lib/config/make.xml
sbsv2/raptor/lib/config/meta.xml
sbsv2/raptor/lib/config/msvc.xml
sbsv2/raptor/lib/config/root.xml
sbsv2/raptor/lib/config/rvct.xml
sbsv2/raptor/lib/config/variants.xml
sbsv2/raptor/lib/config/winscw.xml
sbsv2/raptor/lib/flm/analysis.xml
sbsv2/raptor/lib/flm/base.xml
sbsv2/raptor/lib/flm/bitmap.flm
sbsv2/raptor/lib/flm/booleanlogic.mk
sbsv2/raptor/lib/flm/build.flm
sbsv2/raptor/lib/flm/build.xml
sbsv2/raptor/lib/flm/config.xml
sbsv2/raptor/lib/flm/config/default.flm
sbsv2/raptor/lib/flm/converged-comms/createcommdbs.flm
sbsv2/raptor/lib/flm/converged-comms/installdefaultcommdb.flm
sbsv2/raptor/lib/flm/e32abiv2.flm
sbsv2/raptor/lib/flm/e32abiv2ani.flm
sbsv2/raptor/lib/flm/e32abiv2defaults.mk
sbsv2/raptor/lib/flm/e32abiv2dll.flm
sbsv2/raptor/lib/flm/e32abiv2exe.flm
sbsv2/raptor/lib/flm/e32abiv2exexp.flm
sbsv2/raptor/lib/flm/e32abiv2fsy.flm
sbsv2/raptor/lib/flm/e32abiv2implib.flm
sbsv2/raptor/lib/flm/e32abiv2kdll.flm
sbsv2/raptor/lib/flm/e32abiv2kext.flm
sbsv2/raptor/lib/flm/e32abiv2klib.flm
sbsv2/raptor/lib/flm/e32abiv2ldd.flm
sbsv2/raptor/lib/flm/e32abiv2lib.flm
sbsv2/raptor/lib/flm/e32abiv2none.flm
sbsv2/raptor/lib/flm/e32abiv2pdd.flm
sbsv2/raptor/lib/flm/e32abiv2pdl.flm
sbsv2/raptor/lib/flm/e32abiv2plugin.flm
sbsv2/raptor/lib/flm/e32abiv2stddll.flm
sbsv2/raptor/lib/flm/e32abiv2stdexe.flm
sbsv2/raptor/lib/flm/e32abiv2stdlib.flm
sbsv2/raptor/lib/flm/e32abiv2textnotifier2.flm
sbsv2/raptor/lib/flm/e32abiv2var.flm
sbsv2/raptor/lib/flm/e32abiv2var2.flm
sbsv2/raptor/lib/flm/emulator.xml
sbsv2/raptor/lib/flm/extensions.xml
sbsv2/raptor/lib/flm/final.mk
sbsv2/raptor/lib/flm/flmtools.mk
sbsv2/raptor/lib/flm/gccxml.flm
sbsv2/raptor/lib/flm/gccxmlresource.flm
sbsv2/raptor/lib/flm/globals.mk
sbsv2/raptor/lib/flm/gnumakefile.flm
sbsv2/raptor/lib/flm/grouping.flm
sbsv2/raptor/lib/flm/metaflm.mk
sbsv2/raptor/lib/flm/msvctools.flm
sbsv2/raptor/lib/flm/msvctools.xml
sbsv2/raptor/lib/flm/none.flm
sbsv2/raptor/lib/flm/null.flm
sbsv2/raptor/lib/flm/readme.txt
sbsv2/raptor/lib/flm/resource.flm
sbsv2/raptor/lib/flm/romfile.mk
sbsv2/raptor/lib/flm/stack.mk
sbsv2/raptor/lib/flm/standard.xml
sbsv2/raptor/lib/flm/stringtable.flm
sbsv2/raptor/lib/flm/taggedrules.mk
sbsv2/raptor/lib/flm/template_ext.flm
sbsv2/raptor/lib/flm/test/Makefile
sbsv2/raptor/lib/flm/test/ciaabiv2_1/ciaabiv2_1.mk
sbsv2/raptor/lib/flm/test/ciaabiv2_1/uc_exe.cia
sbsv2/raptor/lib/flm/test/ciaabiv2_1/uc_exe.cpp
sbsv2/raptor/lib/flm/test/ciatests.mk
sbsv2/raptor/lib/flm/test/dllabiv2_1/dllabiv2_1.mk
sbsv2/raptor/lib/flm/test/dllabiv2_1/test.cpp
sbsv2/raptor/lib/flm/test/dllabiv2_defaults.mk
sbsv2/raptor/lib/flm/test/dllbasictests.mk
sbsv2/raptor/lib/flm/test/environment/make/test_variable_restore.mk
sbsv2/raptor/lib/flm/test/environment/pvm/pvmtest.mk
sbsv2/raptor/lib/flm/test/exeabiv2_1/exeabiv2_1.mk
sbsv2/raptor/lib/flm/test/exeabiv2_1/test.cpp
sbsv2/raptor/lib/flm/test/exeabiv2_2/exeabiv2_2.mk
sbsv2/raptor/lib/flm/test/exeabiv2_2/test.cpp
sbsv2/raptor/lib/flm/test/exeabiv2_2/test_function.cpp
sbsv2/raptor/lib/flm/test/exeabiv2_3/exeabiv2_3.mk
sbsv2/raptor/lib/flm/test/exeabiv2_3/test_big.cpp
sbsv2/raptor/lib/flm/test/exeabiv2_4/exeabiv2_4.mk
sbsv2/raptor/lib/flm/test/exeabiv2_4/test.cpp
sbsv2/raptor/lib/flm/test/exeabiv2_4/test_big.cpp
sbsv2/raptor/lib/flm/test/exeabiv2_defaults.mk
sbsv2/raptor/lib/flm/test/exebasictests.mk
sbsv2/raptor/lib/flm/test/exeperftests.mk
sbsv2/raptor/lib/flm/test/export1/Makefile
sbsv2/raptor/lib/flm/test/export1/t1e.h
sbsv2/raptor/lib/flm/test/export1/t2e.h
sbsv2/raptor/lib/flm/test/export1/t3e.h
sbsv2/raptor/lib/flm/test/export1/t4e.h
sbsv2/raptor/lib/flm/test/flmtests.mk
sbsv2/raptor/lib/flm/test/raptorglue/raptorglue.mk
sbsv2/raptor/lib/flm/test/templateext/Makefile
sbsv2/raptor/lib/flm/test/templateext/temex.mk
sbsv2/raptor/lib/flm/tools.xml
sbsv2/raptor/lib/flm/tools/buildstubsis.flm
sbsv2/raptor/lib/flm/tools/stlport.flm
sbsv2/raptor/lib/flm/tools/test_command_diff.sh
sbsv2/raptor/lib/flm/tools2common.flm
sbsv2/raptor/lib/flm/tools2exe.flm
sbsv2/raptor/lib/flm/tools2lib.flm
sbsv2/raptor/lib/flm/tracecompiler.mk
sbsv2/raptor/lib/flm/user/default.flm_ex
sbsv2/raptor/lib/flm/user/globals.mk_ex
sbsv2/raptor/lib/flm/utils/copydir.flm
sbsv2/raptor/lib/flm/utils/prebuilt.flm
sbsv2/raptor/lib/flm/utils/utility.xml
sbsv2/raptor/lib/flm/win32.flm
sbsv2/raptor/lib/flm/win32ani.flm
sbsv2/raptor/lib/flm/win32bitmap.flm
sbsv2/raptor/lib/flm/win32dll.flm
sbsv2/raptor/lib/flm/win32exe.flm
sbsv2/raptor/lib/flm/win32exexp.flm
sbsv2/raptor/lib/flm/win32fsy.flm
sbsv2/raptor/lib/flm/win32implib.flm
sbsv2/raptor/lib/flm/win32kdll.flm
sbsv2/raptor/lib/flm/win32kext.flm
sbsv2/raptor/lib/flm/win32klib.flm
sbsv2/raptor/lib/flm/win32ldd.flm
sbsv2/raptor/lib/flm/win32lib.flm
sbsv2/raptor/lib/flm/win32pdd.flm
sbsv2/raptor/lib/flm/win32pdl.flm
sbsv2/raptor/lib/flm/win32plugin.flm
sbsv2/raptor/lib/flm/win32resource.flm
sbsv2/raptor/lib/flm/win32stddll.flm
sbsv2/raptor/lib/flm/win32stdexe.flm
sbsv2/raptor/lib/flm/win32stdlib.flm
sbsv2/raptor/lib/flm/win32textnotifier2.flm
sbsv2/raptor/lib/flm/win32var.flm
sbsv2/raptor/lib/flm/win32var2.flm
sbsv2/raptor/python/dos2unix.py
sbsv2/raptor/python/filter_interface.py
sbsv2/raptor/python/filter_list.py
sbsv2/raptor/python/filter_utils.py
sbsv2/raptor/python/generic_path.py
sbsv2/raptor/python/mmpparser.py
sbsv2/raptor/python/pluginbox.py
sbsv2/raptor/python/plugins/dummyplugin.py
sbsv2/raptor/python/plugins/filter_carbide.py
sbsv2/raptor/python/plugins/filter_checksource.py
sbsv2/raptor/python/plugins/filter_clean.py
sbsv2/raptor/python/plugins/filter_logfile.py
sbsv2/raptor/python/plugins/filter_splitlog.py
sbsv2/raptor/python/plugins/filter_squashlog.py
sbsv2/raptor/python/plugins/filter_terminal.py
sbsv2/raptor/python/plugins/filter_what.py
sbsv2/raptor/python/pyparsing.py
sbsv2/raptor/python/raptor.py
sbsv2/raptor/python/raptor_cache.py
sbsv2/raptor/python/raptor_cli.py
sbsv2/raptor/python/raptor_data.py
sbsv2/raptor/python/raptor_make.py
sbsv2/raptor/python/raptor_makefile.py
sbsv2/raptor/python/raptor_meta.py
sbsv2/raptor/python/raptor_start.py
sbsv2/raptor/python/raptor_utilities.py
sbsv2/raptor/python/raptor_version.py
sbsv2/raptor/python/raptor_xml.py
sbsv2/raptor/schema/build/1_0.xsd
sbsv2/raptor/schema/build/2_0.xsd
sbsv2/raptor/schema/build/log/1_0.xsd
sbsv2/raptor/util/Makefile
sbsv2/raptor/util/bash.mk
sbsv2/raptor/util/bvcpp.mk
sbsv2/raptor/util/codewarrior.mk
sbsv2/raptor/util/config.h
sbsv2/raptor/util/descramble/Makefile
sbsv2/raptor/util/descramble/descramble.cpp
sbsv2/raptor/util/dialog.mk
sbsv2/raptor/util/gccprogram.mk
sbsv2/raptor/util/gccxml.mk
sbsv2/raptor/util/install-linux/makeself-header.sh
sbsv2/raptor/util/install-linux/makeself.sh
sbsv2/raptor/util/install-linux/package_sbs.sh
sbsv2/raptor/util/install-windows/raptorinstallermaker.py
sbsv2/raptor/util/install-windows/raptorinstallerscript.nsi
sbsv2/raptor/util/install-windows/raptorinstallerutils.nsh
sbsv2/raptor/util/install-windows/unzip.py
sbsv2/raptor/util/make.mk
sbsv2/raptor/util/pvm.mk
sbsv2/raptor/util/pvmgmake.mk
sbsv2/raptor/util/python.mk
sbsv2/raptor/util/ransleep/Makefile
sbsv2/raptor/util/ransleep/ransleep.c
sbsv2/raptor/util/talon/Makefile
sbsv2/raptor/util/talon/buffer.c
sbsv2/raptor/util/talon/buffer.h
sbsv2/raptor/util/talon/lock.c
sbsv2/raptor/util/talon/log.c
sbsv2/raptor/util/talon/log.h
sbsv2/raptor/util/talon/process.c
sbsv2/raptor/util/talon/process.h
sbsv2/raptor/util/talon/process_win.c
sbsv2/raptor/util/talon/sema.c
sbsv2/raptor/util/talon/sema.h
sbsv2/raptor/util/talon/talon.c
sbsv2/raptor/util/talon/talon_process.h
sbsv2/raptor/util/talon/talonctl.c
sbsv2/raptor/util/talon/testbuffer.c
sbsv2/raptor/util/talon/testprocess.c
sbsv2/raptor/util/talon/tests/old_taggedrules.mk
sbsv2/raptor/util/talon/tests/t.mk
sbsv2/raptor/util/talon/tests/t2.mk
sbsv2/raptor/util/talon/tests/t3.mk
sbsv2/raptor/util/talon/tests/t4.mk
sbsv2/raptor/util/talon/tests/t5.mk
sbsv2/raptor/util/talon/tests/taggedrules.mk
sbsv2/raptor/util/talon/tests/xcopystdin.mk
sbsv2/raptor/util/utilbuild.mk
sbsv2/raptor/win32/bin/ransleep.exe
sbsv2/raptor/win32/bin/talon.exe
sbsv2/raptor/win32/bin/talonctl.exe
srctools/tranasm/group/bld.inf
srctools/tranasm/group/tranasm.mrp
--- a/bintools/checklib/group/checklib.mmp	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/checklib/group/checklib.mmp	Wed Jun 23 16:56:47 2010 +0800
@@ -20,6 +20,7 @@
 userinclude     ..
 userinclude     ../object/coff
 userinclude 	../..
+systeminclude   ../../elftools/inc
 
 sourcepath      ..
 
--- a/bintools/checklib/group/checklib.mrp	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/checklib/group/checklib.mrp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/checklib/group/release.txt	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/checklib/object/elf/elf_file_header.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/checklib/object/elf/elf_section_header.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/checklib/object/elf/elf_symbol.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/checklib/object/object.h	Wed Jun 23 16:56:47 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/elftran/elf_dlld.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/elftools/elftran/elf_dlld.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/elftools/elftran/elf_file.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/elftools/elftran/elf_imp.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/elftools/elftran/elf_tran.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/elftools/getexports/geninf.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/elftools/group/bld.inf	Wed Jun 23 16:56:47 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
+../def2dll.pl		/epoc32/tools/def2dll.pl
+../deputil.pl		/epoc32/tools/deputil.pl
+../deputil.pm		/epoc32/tools/deputil.pm
+#endif
+../inc/elfdefs.h	SYMBIAN_OS_LAYER_PLATFORM_EXPORT_PATH(tools/elfdefs.h)
+
+
+PRJ_MMPFILES
+#ifndef TOOLS2_LINUX
+genstubs
+getexports
+elftran
+#endif
+elfdump
+
+
+
+
--- a/bintools/elftools/group/elftools.mrp	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/elftools/group/elftools.mrp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/elftools/group/elftran.mmp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/elftools/group/release.txt	Wed Jun 23 16:56:47 2010 +0800
@@ -1,5 +1,15 @@
-NOTESRC_RELEASER
-Nokia Corporation
-
-NOTESRC_RELEASE_REASON
-ELFtools Release
+NOTESRC_RELEASER
+Nokia Corporation
+
+NOTESRC_RELEASE_REASON
+ELFtools Release
+
+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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/elftools/inc/elfdll.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/elftools/inc/elffile.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/elftools/inc/elftran.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/evalid/dev_build_bintools_evalid.mrp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/evalid/evalid.mrp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/rcomp/group/BLD.INF	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/rcomp/group/RELEASE.TXT	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/rcomp/group/rcomp.mmp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/rcomp/group/rcomp.mrp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/rcomp/inc/VERSION.H	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/rcomp/inc/main.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/rcomp/src/NUMVAL.CPP	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/rcomp/src/RCBINSTR.CPP	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/rcomp/src/RCOMP.LEX	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/rcomp/src/RCOMP.YACC	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/rcomp/src/main.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/rcomp/src/rcomp.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/bintools/rcomp/src/rcompl.cpp	Wed Jun 23 16:56:47 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/buildframework/helium/build.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/buildframework/helium/build.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,58 +1,329 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-============================================================================ 
-Name        : build.xml 
-Part of     : Helium 
-
-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:
-
-============================================================================
--->
-<project name="helium-build" default="help" xmlns:au="org.apache.ant.antunit" xmlns:hlm="http://www.nokia.com/helium"> 
-    <description>
-        Helium targets to build helium itself.
-    </description>
-    <property environment="env" />
-    
-    <property name="build.drive" location="${env.TEMP}/helium/temp_drive"/>
-    <mkdir dir="${build.drive}/"/> 
-    
-    <!--* @property helium.version
-    @type string
-    @scope private -->
-    <property file="${helium.dir}/config/version.txt"/>
-    <property name="release.label" value="${helium.version}"/>
-
-    <property name="doc.src.dir" location="${basedir}/doc/src" />
-    <!-- Override docs targets to do more for Helium. -->
-    <target name="apidocs" depends="python-apidocs,internal.docs.apidocs"/>
-    <!-- Generate rst files for docs -->
-    <target name="prep-textdocs" depends="overview-to-html,tools-rst-table,dependency-diagram,
-        dependency-logs,release-diff,helium-user-graph,internal.docs.prep-textdocs,helium-prep-textdocs"/>
-    <!-- generate all the user documentation for helium -->
-    <target name="docs" depends="clean-docs,database,apidocs,textdocs"/>
-    
-    <import file="helium.ant.xml"/>
-    <import file="tools/startup/antserver/antserver.ant.xml"/>
-    
-    <resources id="textdoc.paths">
-        <path>
-            <pathelement path="${doc.src.dir}"/>
-            <pathelement path="${basedir}/extensions/nokia/doc/src"/>
-        </path>
-    </resources>
-
-</project>
-
+<?xml version="1.0"?>
+<project name="helium-root" default="all">
+    
+    <property environment="env"/>
+    <import file="helium/build.xml"/>
+    
+
+    <property name="helium.svn.workarea.dir" value="\\vcfiler02\proj2\Juno\juno_build_release\helium\svn"/>
+    <property name="helium.ccm.workarea.dir" value="\\vcfiler02\proj2\Juno\juno_build_release\internal\workarea\helium\next"/>
+    <property name="helium.svn.url" value="http://helium.nmp.nokia.com/svn" />
+
+    <target name="unittest">
+        <ant dir="helium" target="unittest" inheritAll="false"/>
+    </target>
+
+    <target name="ant-unittest" depends="xtest-diamonds">
+        <ant dir="helium" target="ant-unittest" inheritAll="false"/>
+    </target>
+
+    <target name="ju-unittest">
+        <ant dir="helium" target="ju-unittest" inheritAll="false"/>
+    </target>
+
+    <target name="py-unittest">
+        <ant dir="helium" target="py-unittest" inheritAll="false"/>
+    </target>
+
+    <target name="check">
+        <ant dir="helium" target="check" inheritAll="false"/>
+    </target>
+
+    <target name="check-distribution-policies">
+        <ant dir="helium" target="delete-svn-unversioned" inheritAll="false"/>
+        <ant dir="helium" target="check-distribution-policies" inheritAll="false"/>
+    </target>
+
+    <target name="pylint">
+        <ant dir="helium" target="pylint" inheritAll="false"/>
+    </target>
+
+    <target name="antlint">
+        <ant dir="helium" target="antlint" inheritAll="false"/>
+    </target>
+
+    <target name="java-checkstyle">
+        <ant dir="helium" target="java-checkstyle" inheritAll="false"/>
+    </target>
+
+    <target name="apidocs">
+        <ant dir="helium" target="apidocs" inheritAll="false"/>
+    </target>
+
+    <target name="textdocs">
+        <ant dir="helium" target="textdocs" inheritAll="false"/>
+    </target>
+
+    <target name="docs">
+        <ant dir="helium" target="docs" inheritAll="false"/>
+    </target>
+
+    <target name="upload-docs">
+        <ant dir="helium" target="upload-docs" inheritAll="false"/>
+    </target>
+
+    <target name="build-zip">
+        <ant dir="helium" target="build-zip" inheritAll="false"/>
+    </target>
+
+    <target name="all" depends="unittest,apidocs,docs,pylint,java-checkstyle"/>
+
+    <!-- Create a new branch from the current working copy.
+    
+    A ${branch} property must be defined for the branch version, e.g. 0.9.x.    
+    --> 
+    <target name="branch" description="Create a new branch from the current working copy">
+        <fail unless="branch">"branch" property not defined, e.g. 0.21.x</fail>
+        <fail unless="version">"version" property not defined, e.g. 0.21</fail>
+        <!-- Major Branches need a reference_branch set -->
+        <if>
+            <contains string="${branch}" substring=".0" />
+            <then>
+                <fail unless="reference_branch">"reference_branch" property not defined, e.g. 0.21</fail>   
+            </then>
+        </if>
+        <if>
+            <not>
+                <isset property="create.branch"/>
+            </not>
+            <then>
+                <input validargs="y,n" addproperty="create.branch">
+A svn branch will be made:
+To: ${helium.svn.url}/helium/branches/helium-${branch}
+Do you want to continue?
+                </input>
+            </then>
+        </if>
+        <if>
+            <equals arg1="${create.branch}" arg2="y"/>
+            <then>
+            	<propertyfile file="helium\config\version.txt" comment="Helium version - DO NOT EDIT">
+                    <entry key="helium.version" value="${version}"/>
+                </propertyfile>
+                <svn username="${env.USERNAME}" password="${env.USERNAME}">
+                	<commit file="helium\config\version.txt"
+                		    message="Updating version to ${version}"/>
+                </svn>
+                <if>
+                    <or>
+                        <not>
+                            <isset property="reference_branch" />                            
+                        </not>
+                        <equals arg1="${reference_branch}" arg2="trunk" />                            
+                    </or>
+                    <then>
+                        <echo message="Create a trunk based branch" />
+                        <!-- Create a Sprint branch -->
+                        <svn username="${env.USERNAME}" password="${env.USERNAME}">
+                            <copy srcurl="${helium.svn.url}/helium/trunk"
+                                  desturl="${helium.svn.url}/helium/branches/helium-${branch}"
+                                  message="Created release branch for helium-${branch} branch based on helium trunk."/>
+                        </svn>
+                    </then>
+                    <else>
+                        <echo message="Create a Sprint based branch" />
+                        <!-- Create a Major branch -->
+                        <svn username="${env.USERNAME}" password="${env.USERNAME}">
+                            <copy srcurl="${helium.svn.url}/helium/branches/helium-${reference_branch}"
+                                  desturl="${helium.svn.url}/helium/branches/helium-${branch}"
+                                  message="Created release branch for helium-${branch} branch based on helium-${reference_branch}."/>
+                            <copy srcurl="${helium.svn.url}/helium/trunk/helium/config/version.txt"
+                                  desturl="${helium.svn.url}/helium/branches/helium-${branch}/helium/config/version.txt"
+                                  message="Updating version to ${version}."/>
+                        </svn>
+                    </else>
+                </if>
+                <svn username="${env.USERNAME}" password="${env.USERNAME}">
+                    <switch path="${helium.svn.workarea.dir}\helium-next"
+                            url="${helium.svn.url}/helium/branches/helium-${branch}"/>
+                </svn>
+            </then>
+        </if>
+    </target>
+
+    <!-- Create a new release tag from the given branch.
+    
+        
+    --> 
+    <target name="release" description="Create a new release tag from the current working copy">
+        <fail unless="branch">"branch" property not defined</fail>
+        <fail unless="version">"version" property not defined</fail>
+        <property name="url" value=""/>
+        <if>
+            <not>
+                <isset property="create.release"/>
+            </not>
+            <then>
+                <input validargs="y,n" addproperty="create.release">
+A svn tag will be made:
+From: ${helium.svn.url}/helium/branches/helium-${branch}
+To  : ${helium.svn.url}/helium/tags/helium-${version}
+Do you want to continue?
+                </input>
+            </then>
+        </if>
+        <if>
+            <equals arg1="${create.release}" arg2="y"/>
+            <then>
+                <echo>Creating release tag from ${helium.svn.url}/helium/branches/helium-${branch}</echo>                
+                <propertyfile file="${helium.svn.workarea.dir}\helium-next\helium\config\version.txt" comment="Helium version - DO NOT EDIT">
+                    <entry key="helium.version" value="${version}"/>
+                </propertyfile>
+                <svn username="${env.USERNAME}" password="${env.USERNAME}">
+                    <commit file="${helium.svn.workarea.dir}\helium-next\helium\config\version.txt" message="Updating version to ${version}"/>
+                </svn>
+                <svn username="${env.USERNAME}" password="${env.USERNAME}" failonerror="false">
+                    <copy srcurl="${helium.svn.url}/helium/branches/helium-${branch}"
+                          desturl="${helium.svn.url}/helium/tags/helium-${version}"
+                          message="Created release tag for helium-${version} release."/>
+                    <switch path="${helium.svn.workarea.dir}\helium-next"
+                            url="${helium.svn.url}/helium/tags/helium-${version}"/>
+                </svn>
+                <exec executable="python" failonerror="true">        
+                    <arg line="bin\trac-add-version.py"/>
+                    <arg value="helium-${version}"/>
+                </exec>
+            </then>
+        </if>
+    </target>
+
+    <target name="merge-svn-to-ccm">
+        <exec executable="c:\apps\bc\bc2.exe">
+            <arg value="@${helium.dir}/tools/common/svn-ccm-sync.bc.txt"/>
+            <arg value="${helium.svn.workarea.dir}\helium-next\helium"/>
+            <arg value="${helium.ccm.workarea.dir}\helium"/>
+            <arg value="c:\svn_ccm_diff.txt"/>
+        </exec>
+    </target>
+
+    <target name="release-email" description="Create a release email HTML content">
+        <fail unless="milestone">"milestone" property not defined (typically sprint name)</fail>
+        <fail unless="release">"release" property not defined</fail>
+        <exec executable="python" failonerror="true">        
+            <arg line="bin\trac-collect-release-email-changes.py"/>
+            <arg value="${milestone}"/>
+        </exec>
+        <fmpp sourceFile="${helium.dir}/extensions/nokia/doc/src/release_notes.html.ftl"
+        	  outputFile="${helium.dir}/build/doc/release_notes_${release}.html">
+            <data expandProperties="yes">
+                doc: xml(${helium.dir}/../release_notes_tickets_${milestone}.xml)
+                cfg: tdd(${helium.dir}/../release_notes_config.txt)
+                ant: antProperties(milestone, release)
+            </data>
+        </fmpp>
+        <fmpp sourceFile="${helium.dir}/extensions/nokia/doc/src/release_notes.rst.ftl"
+        	  outputFile="${helium.dir}/extensions/nokia/doc/src/releasenotes/release_notes_${release}.rst">
+            <data expandProperties="yes">
+                doc: xml(${helium.dir}/../release_notes_tickets_${milestone}.xml)
+                cfg: tdd(${helium.dir}/../release_notes_config.txt)
+                ant: antProperties(milestone, release)
+            </data>
+        </fmpp>
+    </target>
+ 
+    <!-- Get a listing of the number of story points completed in a sprint per user. -->
+    <target name="story-points">
+        <fail unless="milestone">"milestone" property not defined (typically sprint name)</fail>
+        <echo>Story points per developer for ${milestone}:
+        </echo>
+        <exec executable="python" failonerror="true">        
+            <arg line="bin\trac-user-story-points.py"/>
+            <arg value="${milestone}"/>
+        </exec>
+    </target>
+
+    <!-- Shows a dialog allowing the daily SCRUM information to be posted to the Trac wiki. -->
+    <target name="scrum">
+        <antform title="Submit SCRUM notes">
+            <dateProperty label="Date" property="date" dateFormat="yyyy-MM-dd" focus="true"/>
+            <multiLineTextProperty label="Done" property="done"/>
+            <multiLineTextProperty label="Todo" property="todo"/>
+            <multiLineTextProperty label="Blocking" property="blocking"/>
+        </antform>
+        <echo file="scrum_notes.txt">
+== ${env.USERNAME} ==
+   '''Done:''' ${done}
+
+   '''Todo:''' ${todo}
+
+   '''Blocking:''' ${blocking}
+        </echo>
+        <if>
+            <isset property="date"/>
+            <then>
+                <echo>${done}</echo>
+                <property name="page" value="Scrum/Log/${date}"/>
+                <property name="done" value="None"/>
+                <property name="todo" value="None"/>
+                <property name="blocking" value="None"/>
+                <exec executable="python" failonerror="true">        
+                    <arg line="bin\trac-update-scrum-notes.py"/>
+                    <arg line="--file scrum_notes.txt ${page}"/>
+                </exec>   
+            </then>
+        </if>
+    </target>
+
+    <!-- Install BBControllerService.py and start the service to control Buildbot service -->
+    <target name="install-bb-controller-service">
+        <copy file="bin\BBControllerService.py" tofile="c:\apps\actpython\Lib\site-packages\BBControllerService.py"/>
+        <exec osfamily="windows" executable="python" failonerror="true">            
+            <env key="PYTHONPATH" value="${env.PYTHONPATH};${python.modules.path}"/>
+            <arg line="c:\apps\actpython\Lib\site-packages\BBControllerService.py"/>
+            <arg line="--startup auto"/> 
+            <arg line="install"/>
+        </exec>
+        <exec osfamily="windows" executable="python" failonerror="true">            
+            <env key="PYTHONPATH" value="${env.PYTHONPATH};${python.modules.path}"/>
+            <arg line="c:\apps\actpython\Lib\site-packages\BBControllerService.py"/>
+            <arg line="start"/>
+        </exec>
+    </target>
+
+    <!-- Use this target to restart a Helium buildbot service. BBControllerService.py service
+    must be installed in buildbot machine.
+    Usage:
+    <pre>
+        Usage: hlm restart-buildbot -Dbb.machine=[Buildbot machine name] -Dbb.command=[BB_RESTART]
+    </pre>  -->
+    <target name="restart-buildbot">
+        <script language="jython" setbeans="false">
+import os
+import socket
+import time
+import sys
+import traceback
+
+bbmachie = project.getProperty("bb.machine")
+cmd = project.getProperty("bb.cmd")
+
+if bbmachie == None or cmd == None :
+    print "Buildbot machine name and/or Command not found."
+    print "Usage: hlm restart-buildbot -Dbb.machine=[Buildbot machine name] -Dbb.cmd=[BB_RESTART]"
+else :    
+    sockt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)        
+    try:
+        sockt.connect((bbmachie, int(50008)))
+        sockt.send(cmd)    
+        data = sockt.recv(1024)
+        print "Response: ", data
+    except:
+        print "Buildbot machine is busy or not found."
+        traceback.print_exc()
+    sockt.close()       
+        </script>
+    </target>
+
+    <target name="coffee">
+        <splash imageurl="file:////${helium.dir}/../coffee.png" showduration="5000"/>
+    </target>
+
+    <!-- Create a zip file of Helium for release via Hydra -->    
+    <target name="helium-hydra-zip">
+        <delete file="${env.TEMP}/helium-${helium.version}.zip" failonerror="false"/>  
+        <zip destfile="${env.TEMP}/helium-${helium.version}.zip">
+            <zipfileset dir="./helium" prefix="helium"/>
+        </zip>
+    </target>
+
+</project>
\ No newline at end of file
--- a/buildframework/helium/hlm.bat	Wed Jun 16 16:51:40 2010 +0300
+++ b/buildframework/helium/hlm.bat	Wed Jun 23 16:56:47 2010 +0800
@@ -1,156 +1,6 @@
 @echo off
 
-rem
-rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
-rem All rights reserved.
-rem This component and the accompanying materials are made available
-rem under the terms of the License "Eclipse Public License v1.0"
-rem which accompanies this distribution, and is available
-rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
-rem
-rem Initial Contributors:
-rem Nokia Corporation - initial contribution.
-rem
-rem Contributors:
-rem
-rem Description: 
-rem
-
-setlocal
-
-REM Set the Helium location
-REM Make sure the path is not ending with a backslash!
-if not defined HELIUM_HOME (
-	set HELIUM_HOME_TEMP=%~dp0
-)
-if not defined HELIUM_HOME (
-	set HELIUM_HOME=%HELIUM_HOME_TEMP:~0,-1%
-)
-
-rem Loading runtime environment tools
-if exist "%HELIUM_HOME%\runtime\runtime_env.bat" (
-call %HELIUM_HOME%\runtime\runtime_env.bat
-) 
-
-if not exist "%HELIUM_HOME%\extensions\nokia\build.xml" ( 
-set HLM_SUBCON=1
-set HLM_DISABLE_INTERNAL_DATA=1
-)
-
-
-REM Configure Java
-if not defined JAVA_6_HOME (
-set TESTED_JAVA=C:\Apps\j2sdk_1.6.0_02
-) ELSE  set TESTED_JAVA=%JAVA_6_HOME%
-if exist "%TESTED_JAVA%" (set JAVA_HOME=%TESTED_JAVA%)
-if not exist "%JAVA_HOME%" ( echo *** Java cannot be found & goto :errorstop )
-set PATH=%JAVA_HOME%\bin;%PATH%
-
-REM Needed by python logging
-set PID=1
-perl "%HELIUM_HOME%\tools\common\bin\getppid.pl" > %TEMP%\%USERNAME%pid.txt
-set /p PID=< %TEMP%\%USERNAME%pid.txt
-
-REM Configure Apache Ant
-if not defined TESTED_ANT (
-  set TESTED_ANT=C:\APPS\ant_1.7
-)
-if exist "%TESTED_ANT%" (set ANT_HOME=%TESTED_ANT%)
-if not exist "%ANT_HOME%" ( echo *** Ant cannot be found & goto :errorstop )
-if not defined ANT_OPTS (
-	set ANT_OPTS=-Xmx896M -Dlog4j.configuration=com/nokia/log4j.xml
-)
-
-set SIGNALING_ANT_ARGS= -Dant.executor.class=com.nokia.helium.core.ant.HeliumExecutor
-set LOGGING_ANT_ARGS= -listener com.nokia.helium.logger.ant.listener.StatusAndLogListener
-REM -listener com.nokia.helium.logger.ant.listener.StatusAndLogListener
-set DIAMONDS_ANT_ARGS= -listener com.nokia.helium.diamonds.ant.HeliumListener
-
-if not defined HLM_DISABLE_INTERNAL_DATA (
-set INTERNAL_DATA_ANT_ARGS= -listener com.nokia.helium.internaldata.ant.listener.Listener
-echo Internal data listening enabled.
-)
-
-
-REM Configure listener to generate target times csv file.
-REM **Note: Comment below line if you want to skip the target times csv file generation
-set TARGET_TIMES_GENERATOR= -listener com.nokia.helium.core.ant.listener.TargetTimesLogGeneratorListener
-
+rem if not defined HELIUM_HOME set HELIUM_HOME=%~dp0..\..\..\helium
 
-if not defined ANT_ARGS (
-set ANT_ARGS=-lib "%HELIUM_HOME%\external\antlibs2" -lib "%HELIUM_HOME%\extensions\nokia\external\antlibs" -logger com.nokia.ant.HeliumLogger  %DIAMONDS_ANT_ARGS% %INTERNAL_DATA_ANT_ARGS% %SIGNALING_ANT_ARGS% %LOGGING_ANT_ARGS% %TARGET_TIMES_GENERATOR%
-)
-
-REM Shall we impose the EPOCROOT?
-if not defined EPOCROOT (
-set EPOCROOT=\
-)
-
-REM Symbian Build area path related settings
-set PATH=%PATH%;%EPOCROOT%epoc32\tools;%EPOCROOT%epoc32\gcc\bin;%EPOCROOT%epoc32\tools\build;%EPOCROOT%epoc32\rombuild
-
-set PATH=%PATH%;%HELIUM_HOME%\extensions\nokia\external\unxutils
-set PATH=%PATH%;%HELIUM_HOME%\extensions\nokia\external\Subversion\bin
-set PATH=%PATH%;%HELIUM_HOME%\extensions\nokia\external\graphviz\bin
-
-for /f "tokens=2" %%a in ('"python -V 2>&1"') do (set pythonversion=%%a)
-for /f "tokens=1-2 delims=." %%a in ("%pythonversion%") do (set pythonversion=%%a.%%b)
-
-set PYTHONPATH=%HELIUM_HOME%\external\python\lib\auto;%HELIUM_HOME%\external\python\lib\%pythonversion%
-set PYTHONPATH=%PYTHONPATH%;%HELIUM_HOME%\external\python\lib\common;%HELIUM_HOME%\tools\common\python\scripts
-set PYTHONPATH=%PYTHONPATH%;%HELIUM_HOME%\extensions\nokia\external\python\lib\%pythonversion%
-set PYTHONPATH=%PYTHONPATH%;%HELIUM_HOME%\extensions\nokia\tools\common\python\lib;%SBS_HOME%\python
-set PERL5LIB=%HELIUM_HOME%\tools\common\packages
-set COPYCMD=/y
-
-REM Should be done that SYMSEE?
-set PATH=%PATH%;C:\APPS\ctc
-
-REM Nokia specific
-set HOME=h:\
-set ARMROOT=\
-
+helium\hlm.bat %*
 
-REM Manage RVCT switching.
-if defined HLM_RVCT_VERSION (
-if not exist "C:\APPS\rvct%HLM_RVCT_VERSION%\rvctcmdprompt.bat" ( echo *** "C:\APPS\rvct%HLM_RVCT_VERSION%\rvctcmdprompt.bat" cannot be found & goto :errorstop )
-call "C:\APPS\rvct%HLM_RVCT_VERSION%\rvctcmdprompt.bat" > nul
-)
-TITLE Helium
-
-if not exist "%HELIUM_HOME%\external\antlibs2\helium-checktools-1.0.jar" (
-echo *** Error: Please build helium from nokia_builder or builder dir run "bld && bld get-deps"
-goto errorstop
-)
-
-call "%JAVA_HOME%\bin\java" -cp "%HELIUM_HOME%\external\antlibs2\helium-checktools-1.0.jar" com.nokia.helium.checktools.HeliumToolsCheckerMain -config "%HELIUM_HOME%\config\helium.basic.tools.config"
-if not defined HLM_DISABLE_TOOL_CHECK (
-if "%ERRORLEVEL%" neq "0" (goto errorstop)
-)
-
-REM Call the Helium generated batch file if it exists
-REM This must match with the cache.dir property in helium.ant.xml
-if defined JOB_ID  (
-	set HELIUM_CACHE_DIR=%TEMP%\helium\%USERNAME%\%JOB_ID%
-)ELSE set HELIUM_CACHE_DIR=%TEMP%\helium\%USERNAME%
-
-if not exist %HELIUM_CACHE_DIR% (
-md %HELIUM_CACHE_DIR%
-)
-
-REM pass cache dir to a property for log4j log file
-if defined ANT_OPTS (
-	set ANT_OPTS=%ANT_OPTS% -Dlog4j.cache.dir=%HELIUM_CACHE_DIR% 
-    call %HELIUM_HOME%\external\python\configure_jython.bat
-)
-
-call ant -Dhelium.dir="%HELIUM_HOME%" -Dcache.dir="%HELIUM_CACHE_DIR%" %*
-
-endlocal
-goto :eof
-
-:errorstop
-@echo *** Build aborted with error
-exit /b 1
-
-
--- a/e32tools/e32lib/group/bld.inf	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/e32lib/group/bld.inf	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/e32lib/group/e32lib.mrp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/e32lib/group/release.txt	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/e32lib/group/seclib.mmp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/e32lib/seclib/seclib.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/e32lib/setcap/setcap.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/elf2e32/group/elf2e32.mmp	Wed Jun 23 16:56:47 2010 +0800
@@ -27,9 +27,9 @@
 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
 
-systeminclude    /epoc32/include  /epoc32/include/tools  
-userinclude		../source ../include
+userinclude		../source ../include ../../../bintools/elftools/inc
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
 
-option 	GCC -w
+option 	GCC -O2 -w
 
 VENDORID 0x70000001
--- a/e32tools/elf2e32/group/elf2e32.mrp	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/elf2e32/group/elf2e32.mrp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/elf2e32/group/release.txt	Wed Jun 23 16:56:47 2010 +0800
@@ -3,3 +3,23 @@
 
 NOTESRC_RELEASE_REASON
 Postlinker(elf2e32) Release
+
+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	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/elf2e32/include/h_ver.h	Wed Jun 23 16:56:47 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=3;
 
 #endif
 
--- a/e32tools/elf2e32/source/deflatecompress.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/elf2e32/source/deflatecompress.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/elf2e32/source/e32imagefile.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1177,6 +1177,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; 
 }
 
 /**
--- a/e32tools/elf2e32/source/e32imagefile.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/elf2e32/source/e32imagefile.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/elf2e32/source/elffilesupplied.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/elf2e32/source/filedump.cpp	Wed Jun 23 16:56:47 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/h_utl.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/elf2e32/source/h_utl.h	Wed Jun 23 16:56:47 2010 +0800
@@ -11,7 +11,7 @@
 // Contributors:
 //
 // Description:
-//
+
 
 
  #ifndef __H_UTL_H__
--- a/e32tools/elf2e32/source/imgdump.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/elf2e32/source/imgdump.cpp	Wed Jun 23 16:56:47 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/pagedcompress.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/elf2e32/source/pagedcompress.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -270,32 +270,26 @@
 }
 
 
-void CompressPages(TUint8 * bytes, TInt size, std::ofstream& os)
+void CompressPages(TUint8* bytes, TInt size, std::ofstream& os)
 {
 	// Build a list of compressed pages
-	TUint16 numOfPages = (TUint16) (size / PAGE_SIZE);
-	if ( size % PAGE_SIZE > 0)
-		++numOfPages;
+	TUint16 numOfPages = (TUint16) ((size + PAGE_SIZE - 1) / PAGE_SIZE);
 	
-	CBytePairCompressedImage *comprImage = CBytePairCompressedImage::NewLC(numOfPages, size);
-	if( NULL == comprImage)
+	CBytePairCompressedImage* comprImage = CBytePairCompressedImage::NewLC(numOfPages, size);
+	if (!comprImage)
 	{
 		//Print(EError," NULL == comprImage\n");
 		return;
 	}
 	
-	TUint8* iPageStart;
-	TUint16 iPageLen;
-	TUint16 iPage = 0;
-	
-	while(iPage * PAGE_SIZE <= size )
+	TUint pageNum;
+	TUint remain = (TUint)size;
+	for (pageNum=0; pageNum<numOfPages; ++pageNum)
 	{
-		iPageStart = &bytes[iPage * PAGE_SIZE];
-		iPageLen = (TUint16)( (iPage + 1) * PAGE_SIZE < size ? PAGE_SIZE : size - iPage * PAGE_SIZE);
-		
-		comprImage->AddPage(iPage, iPageStart, iPageLen);
-
-		++iPage;
+		TUint8* pageStart = bytes + pageNum * PAGE_SIZE;
+		TUint pageLen = remain>PAGE_SIZE ? PAGE_SIZE : remain;
+		comprImage->AddPage((TUint16)pageNum, pageStart, (TUint16)pageLen);
+		remain -= pageLen;
 	}
 	
 	// Write out index table and compressed pages
@@ -307,6 +301,7 @@
 	
 }
 
+
 int DecompressPages(TUint8 * bytes, std::ifstream& is)
 {
 	TUint decompressedSize = 0;
--- a/e32tools/elf2e32/source/parametermanager.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/e32tools/elf2e32/source/parametermanager.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -25,6 +25,7 @@
 #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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/group/BLD.INF	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/group/buildrom.mrp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/group/release.txt	Wed Jun 23 16:56:47 2010 +0800
@@ -1,45 +1,155 @@
-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.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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/CODESIZE.PL	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/CONVERT.PL	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/Dep_Lister.pm	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/GenericParser.pm	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/ImageContentHandler.pm	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/buildrom.pl	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/buildrom.pm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,4654 +1,5161 @@
-#
-# 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 = 24;
+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   
+   -chechcase                       -- 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-^(.:)?\/--o;		    # remove drive letter and leading backslash
+
+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 $invokecmddir = "";
+
+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);
+	push (@otherDirs, $invokecmddir) if ($invokecmddir ne "");
+
+	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;		
+			next;
+	  }elsif ($arg =~ /^-workdir=(.*)/)
+		{
+			my $workdir=$1;
+			if( $workdir =~ m/ / )
+			{
+				print "* Warning: $workdir contains whitespace, hence the files will be created in default location \n";
+				$workdir = "";
+			}
+			if ($workdir ne "")
+			{
+				$invokecmddir = cwd;
+				$invokecmddir=~s-\\-\/-go;		    # separator from Perl 5.005_02+ is forward slash
+				$invokecmddir.= "\/" unless $invokecmddir =~ /\/$/;
+				$workdir =~ s-\\-\/-g;
+				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 =~ /\/$/;
+				$thisdir=~s-^(.:)?\/--o;		    # remove drive letter and leading backslash
+			}
+			next;	
+		}
+	}
+	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=(.*)/)
+		{
+			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
+{
+	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\"";
+		$cppargs .= " -I \"$invokecmddir\"" if ($invokecmddir ne "");
+	}
+
+	print "* cpp -Wno-endif-labels -o tmp1.oby $cppargs\n" if ($opt_v);
+	
+	is_existinpath("cpp", romutl::DIE_NOT_FOUND);
+	$errors = 0;
+	open CPP, "| cpp -Wno-endif-labels -o tmp1.oby $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 "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";
+				$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, "tmp1.oby" or die("* Can't open tmp1.oby\n");
+	while ($line=<TMP1>)
+	{
+		track_source($line);
+		$line =~ s-\\-\/-g;
+		#
+		# 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;
+			$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 = $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;
+			}
+			# for -workdir option, to support relative path to the call path
+			if (!$fileExists && ($invokecmddir ne "") && ($filename !~ /^([\\\/]|.:)/))
+			{
+				if (-e $invokecmddir.$filename)
+				{
+					$fileExists = $invokecmddir.$filename;
+				}
+			}
+			
+			# 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/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*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+"\/?(.*)"(.*)$/)
+	{
+		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(&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 "")
+	{
+		$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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/cdfparser.pm	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/datadriveimage.pm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,727 +1,740 @@
-#
-# 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+)\s+(\S+)/i )
+		{
+			my $keyWord=$1;
+			my $source=$2;
+			my $dest=$3;
+
+			if( $source !~ /(\S+):(\S+)/ )
+			{ 
+				$source = get_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);
+	
+	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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/efficient_rom_paging.pm	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/externaltools.pm	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/featurefile.pm	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/featuremanager.pm	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/featureparser.pm	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/features.pl	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/features.pm	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/featuresutil.pm	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/spitool.pl	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/buildrom/tools/spitool.pm	Wed Jun 23 16:56:47 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/imaker/buildrom_plugins/group/bld.inf	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/buildrom_plugins/group/bld.inf	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 * 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 "Symbian Foundation License v1.0"
+* under the terms of the License "Eclipse Public License v1.0"
 * which accompanies this distribution, and is available
-* at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
 *
 * Initial Contributors:
 * Nokia Corporation - initial contribution.
--- a/imgtools/imaker/buildrom_plugins/hide.pm	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/buildrom_plugins/hide.pm	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/buildrom_plugins/localise.pm	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/buildrom_plugins/localise.pm	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/buildrom_plugins/localise_all_resources.pm	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/buildrom_plugins/localise_all_resources.pm	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/buildrom_plugins/obyparse.pm	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/buildrom_plugins/obyparse.pm	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/buildrom_plugins/override.pm	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/buildrom_plugins/override.pm	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/buildrom_plugins/plugincommon.pm	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/buildrom_plugins/plugincommon.pm	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/config/example_image_conf_buildinfo.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/config/example_image_conf_buildinfo.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/config/example_image_conf_naming.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/config/example_image_conf_naming.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/config/example_image_conf_platform.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/config/example_image_conf_platform.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/config/example_image_conf_product.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/config/example_image_conf_product.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/config/example_imaker_extension.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/config/example_imaker_extension.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/config/example_language_variant.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/config/example_language_variant.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/config/example_system_languages.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/config/example_system_languages.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/config/group/bld.inf	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/config/group/bld.inf	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 * 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 "Symbian Foundation License v1.0"
+* under the terms of the License "Eclipse Public License v1.0"
 * which accompanies this distribution, and is available
-* at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
 *
 * Initial Contributors:
 * Nokia Corporation - initial contribution.
--- a/imgtools/imaker/group/bld.inf	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/group/bld.inf	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 * 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 "Symbian Foundation License v1.0"
+* under the terms of the License "Eclipse Public License v1.0"
 * which accompanies this distribution, and is available
-* at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
 *
 * Initial Contributors:
 * Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker.cmd	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker.cmd	Wed Jun 23 16:56:47 2010 +0800
@@ -3,9 +3,9 @@
 rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
 rem All rights reserved.
 rem This component and the accompanying materials are made available
-rem under the terms of the License "Symbian Foundation License v1.0"
+rem under the terms of the License "Eclipse Public License v1.0"
 rem which accompanies this distribution, and is available
-rem at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
 rem
 rem Initial Contributors:
 rem Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker.pl	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker.pl	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker.pm	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker.pm	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker_core.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker_core.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker_help.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker_help.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker_image.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker_image.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker_minienv.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker_minienv.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker_odp.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker_odp.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker_public.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker_public.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker_rofs2.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker_rofs2.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker_rofs3.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker_rofs3.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker_rofs4.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker_rofs4.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker_tools.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker_tools.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker_uda.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker_uda.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker_variant.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker_variant.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imaker/src/imaker_version.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imaker/src/imaker_version.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -2,9 +2,9 @@
 # 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 "Symbian Foundation License v1.0"
+# under the terms of the License "Eclipse Public License v1.0"
 # which accompanies this distribution, and is available
-# at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html".
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
 #
 # Initial Contributors:
 # Nokia Corporation - initial contribution.
--- a/imgtools/imgcheck/group/bld.inf	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/group/bld.inf	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/group/imgcheck.mmp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/group/imgcheck.mrp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/group/imgutils.mmp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/group/release.txt	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/imagechekunittest/testcode/cmdlinehandletest.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/checker.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/cmdlinehandler.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/cmdlinewriter.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/common.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/dbgflagchecker.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/depchecker.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/exceptionimplementation.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/exceptionreporter.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/hash.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/imgcheckmanager.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/reporter.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/reportwriter.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/sidchecker.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/version.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/vidchecker.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/inc/xmlwriter.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/inc/dirreader.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/inc/e32reader.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/inc/imagereader.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/inc/rofsreader.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/inc/romfsentry.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/inc/romreader.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/inc/typedefs.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/inc/utils.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/src/dirreader.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/src/e32reader.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/src/imagereader.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/src/rofsimage.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/src/rofsreader.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/src/romimageheader.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/src/romreader.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/libimgutils/src/utils.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/src/checker.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/src/cmdlinehandler.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/src/cmdlinewriter.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/src/common.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/src/dbgflagchecker.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/src/depchecker.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/src/exceptionimplementation.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/src/exceptionreporter.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/src/hash.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/src/imgcheckmanager.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/src/main.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/src/reporter.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/src/sidchecker.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/src/vidchecker.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imgcheck/src/xmlwriter.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/compress/byte_pair.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/compress/byte_pair.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/compress/pagedcompress.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/e32image/deflate/deflate.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/e32image/e32image.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/e32image/imgdump.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/e32image/tr_main.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/e32uid/e32uid.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/e32uid/uidcrc.cpp	Wed Jun 23 16:56:47 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/filesystem/include/cluster.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/include/cluster.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,72 +1,72 @@
-/*
-* 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: 
-* Cluster class for FileSystem component
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef CLUSTER_H
-#define CLUSTER_H
-
-#include "errorhandler.h"
-#include "directory.h"
-
-typedef std::multimap <unsigned int,unsigned int> TClustersPerEntryMap;
-
-/*
- * This class is used by classes CDirRegion and CLongName. This class describes 
- * the basic Data members and Member functions related to cluster number 
- * allocation and FAT input map creation.
- *
- * @internalComponent
- * @released
- */
-
-class CCluster
-{
-	public:
-		static CCluster* Instance (unsigned int aClusterSize, 
-								   unsigned int aTotalNumberOfClusters);
-
-		unsigned int GetCurrentClusterNumber() const;
-		void DecrementCurrentClusterNumber();
-		unsigned short int GetHighWordClusterNumber() const;
-		unsigned short int GetLowWordClusterNumber() const;
-		void CreateMap(unsigned int aStartingClusterNumber,unsigned int aPairClusterNumber);
-		TClustersPerEntryMap* GetClustersPerEntryMap();
-		void UpdateNextAvailableClusterNumber();
-		unsigned int GetClusterSize() const;
-		~CCluster ();
-
-	private:
-		CCluster(unsigned int aClusterSize,
-				 unsigned int aTotalNumberOfClusters);
-		static CCluster* iClusterInstance;
-
-		unsigned long int iClusterSize;
-		unsigned int iRootClusterNumber;
-		unsigned int iCurrentClusterNumber;
-		unsigned int iTotalNumberOfClusters;
-
-		
-		/* used to store the mapping of Starting cluster and Number's of
-		 * clusters occupied by the specific entry
-		 */
-		TClustersPerEntryMap iClustersPerEntry;
-};
-
-#endif //CLUSTER_H
+/*
+* 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: 
+* Cluster class for FileSystem component
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef CLUSTER_H
+#define CLUSTER_H
+
+#include "errorhandler.h"
+#include "directory.h"
+
+typedef multimap <unsigned int,unsigned int> TClustersPerEntryMap;
+
+/*
+ * This class is used by classes CDirRegion and CLongName. This class describes 
+ * the basic Data members and Member functions related to cluster number 
+ * allocation and FAT input map creation.
+ *
+ * @internalComponent
+ * @released
+ */
+
+class CCluster
+{
+	public:
+		static CCluster* Instance (unsigned int aClusterSize, 
+								   unsigned int aTotalNumberOfClusters);
+
+		unsigned int GetCurrentClusterNumber() const;
+		void DecrementCurrentClusterNumber();
+		unsigned short int GetHighWordClusterNumber() const;
+		unsigned short int GetLowWordClusterNumber() const;
+		void CreateMap(unsigned int aStartingClusterNumber,unsigned int aPairClusterNumber);
+		TClustersPerEntryMap* GetClustersPerEntryMap();
+		void UpdateNextAvailableClusterNumber();
+		unsigned int GetClusterSize() const;
+		~CCluster ();
+
+	private:
+		CCluster(unsigned int aClusterSize,
+				 unsigned int aTotalNumberOfClusters);
+		static CCluster* iClusterInstance;
+
+		unsigned long int iClusterSize;
+		unsigned int iRootClusterNumber;
+		unsigned int iCurrentClusterNumber;
+		unsigned int iTotalNumberOfClusters;
+
+		
+		/* used to store the mapping of Starting cluster and Number's of
+		 * clusters occupied by the specific entry
+		 */
+		TClustersPerEntryMap iClustersPerEntry;
+};
+
+#endif //CLUSTER_H
--- a/imgtools/imglib/filesystem/include/directory.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/include/directory.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,158 +1,189 @@
-/*
-* 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: 
-* Directory operations for FileSystem component
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef DIRECTORY_H
-#define DIRECTORY_H
-
-#include "utils.h"
-
-/* If the macro _FILESYSTEM_DLL is defined, then the macro FILESYSTEM_API is used to 
- * export the functions. Hence while building the DLL this macro should be used.
- * Else if the macro _USE_FILESYSTEM_DLL is defined, then the macro FILESYSTEM_API is 
- * used to import the functions. Hence while linking this macro should be used.
- * If none of the above macros defined, then the macro FILESYSTEM_API is defined empty 
- * and it is used for creating static library.
- * The purpose of using multiple macros is to deliver both the static and dynamic 
- * libraries from the same set of source files.
- */
-#ifdef _FILESYSTEM_DLL
-	#define FILESYSTEM_API __declspec(dllexport)
-#elif _USE_FILESYSTEM_DLL
-	#define FILESYSTEM_API __declspec(dllimport)
-#else
-	#define FILESYSTEM_API
-#endif
-
-#include <list>
-#include <stack>
-#include <time.h>
-
-class CDirectory;
-class CLongEntry;
-
-typedef std::list<CDirectory*> EntryList;
-
-//Directory, file and volume Attributes
-enum KAttributes
-{
-	EAttrReadOnly = 0x01,
-	EAttrHidden = 0x02,
-	EAttrSystem = 0x04,
-	EAttrVolumeId = 0x08,
-	EAttrDirectory = 0x10,
-	EAttrArchive = 0x20,
-	EAttrLongName = EAttrReadOnly | EAttrHidden | EAttrSystem | EAttrVolumeId,
-	EAttrLongNameMask = EAttrReadOnly | EAttrHidden | EAttrSystem | EAttrVolumeId \
-						| EAttrDirectory | EAttrArchive,
-	ELastLongEntry = 0x40
-};
-
-//Time format, should be written as a integer in FAT image
-typedef struct 
-{
-	unsigned short int Seconds:5;
-	unsigned short int Minute:6;
-	unsigned short int Hour:5;
-}FatTime;
-
-//Date format, should be written as a integer in FAT image
-typedef struct 
-{
-	unsigned short int Day:5;
-	unsigned short int Month:4;
-	unsigned short int Year:7;
-}FatDate;
-
-//This union convention used to convert bit fields into integer
-union TDateInteger
-{
-	FatDate iCurrentDate;
-	unsigned short int iImageDate;
-};
-
-//This union convention used to convert bit fields into integer
-union TTimeInteger
-{	
-	FatTime iCurrentTime;
-	unsigned short int iImageTime;
-};
-
-/* This class describes the attributes of a single directory/file/volume entry.
- *
- * @internalComponent
- * @released
- */
-class CDirectory
-{
-
-public:
-	FILESYSTEM_API CDirectory(char* aEntryName);
-	FILESYSTEM_API ~CDirectory();
-	FILESYSTEM_API EntryList* GetEntryList();
-	FILESYSTEM_API void InsertIntoEntryList(CDirectory* aEntry);
-	FILESYSTEM_API void SetFilePath(char* aFilePath);
-	FILESYSTEM_API String GetFilePath() const;
-	FILESYSTEM_API void SetEntryName(String aEntryName);
-	FILESYSTEM_API String GetEntryName() const;
-	FILESYSTEM_API void SetEntryAttribute(char aAttribute);
-	FILESYSTEM_API char GetEntryAttribute() const;
-	char GetNtReservedByte() const;
-	char GetCreationTimeMsecs() const;
-	unsigned short int GetCreatedTime() const;
-	unsigned short int GetCreationDate() const;
-	unsigned short int GetLastAccessDate() const;
-	unsigned short int GetClusterNumberHi() const;
-	void SetClusterNumberHi(unsigned short int aHiClusterNumber);
-	unsigned short int GetClusterNumberLow() const;
-	void SetClusterNumberLow(unsigned short int aLowClusterNumber);
-	unsigned short int GetLastWriteDate() const;
-	unsigned short int GetLastWriteTime() const;
-	FILESYSTEM_API void SetFileSize(unsigned int aFileSize);
-	FILESYSTEM_API unsigned int GetFileSize() const;
-	bool IsFile() const ;
-
-private:
-	void InitializeTime();
-
-private:
-	String iEntryName;					//Directory or file name
-	char iAttribute;					//To mention file or directory or Volume
-	char iNtReserved;					//Reserved for use by windows NT, this value always zero
-	char iCreationTimeMsecs;			/**Millisecond stamp at file creation time, Since this is not 
-	so important, always initialized to zero*/
-	unsigned short int iCreatedTime;	//Time file was created
-	unsigned short int iCreationDate;	//Date file was created
-	unsigned short int iLastAccessDate;	//Date file was last accessed
-	unsigned short int iClusterNumberHi;//High word of this entry's first cluster number
-	unsigned short int iClusterNumberLow;//Low word of this entry's first cluster number
-	unsigned short int iLastWriteDate;	//Date file was written
-	unsigned short int iLastWriteTime;	//Time file was written
-	unsigned int iFileSize;				//file size
-	EntryList iDirectoryList;			//List Template used to hold subdirectories
-	
-	String iFilePath; //Holds file path only if the entry is of type "file"
-
-	struct tm* iDateAndTime;
-	union TTimeInteger iTime;
-	union TDateInteger iDate;
-};
-
-#endif //DIRECTORY_H
+/*
+* 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: 
+* Directory operations for FileSystem component
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef DIRECTORY_H
+#define DIRECTORY_H
+
+#include "utils.h"
+
+/* If the macro _FILESYSTEM_DLL is defined, then the macro FILESYSTEM_API is used to 
+ * export the functions. Hence while building the DLL this macro should be used.
+ * Else if the macro _USE_FILESYSTEM_DLL is defined, then the macro FILESYSTEM_API is 
+ * used to import the functions. Hence while linking this macro should be used.
+ * If none of the above macros defined, then the macro FILESYSTEM_API is defined empty 
+ * and it is used for creating static library.
+ * The purpose of using multiple macros is to deliver both the static and dynamic 
+ * libraries from the same set of source files.
+ */
+#ifdef _FILESYSTEM_DLL
+	#define FILESYSTEM_API __declspec(dllexport)
+#elif _USE_FILESYSTEM_DLL
+	#define FILESYSTEM_API __declspec(dllimport)
+#else
+	#define FILESYSTEM_API
+#endif
+
+#include <list>
+#include <stack>
+#include <time.h>
+
+class CDirectory;
+class CLongEntry;
+
+typedef list<CDirectory*> EntryList;
+
+//Directory, file and volume Attributes
+enum KAttributes
+{
+	EAttrReadOnly = 0x01,
+	EAttrHidden = 0x02,
+	EAttrSystem = 0x04,
+	EAttrVolumeId = 0x08,
+	EAttrDirectory = 0x10,
+	EAttrArchive = 0x20,
+	EAttrLongName = EAttrReadOnly | EAttrHidden | EAttrSystem | EAttrVolumeId,
+	EAttrLongNameMask = EAttrReadOnly | EAttrHidden | EAttrSystem | EAttrVolumeId \
+						| EAttrDirectory | EAttrArchive,
+	ELastLongEntry = 0x40
+};
+
+//Time format, should be written as a integer in FAT image
+typedef struct 
+{
+	unsigned short int Seconds:5;
+	unsigned short int Minute:6;
+	unsigned short int Hour:5;
+}FatTime;
+
+//Date format, should be written as a integer in FAT image
+typedef struct 
+{
+	unsigned short int Day:5;
+	unsigned short int Month:4;
+	unsigned short int Year:7;
+}FatDate;
+
+//This union convention used to convert bit fields into integer
+union TDateInteger
+{
+	FatDate iCurrentDate;
+	unsigned short int iImageDate;
+};
+
+//This union convention used to convert bit fields into integer
+union TTimeInteger
+{	
+	FatTime iCurrentTime;
+	unsigned short int iImageTime;
+};
+
+struct TShortDirEntry {
+    unsigned char DIR_Name [11];
+    unsigned char DIR_Attr ;
+    unsigned char DIR_NTRes ;
+    unsigned char DIR_CrtTimeTenth ;
+    unsigned char DIR_CrtTime[2] ;
+    unsigned char DIR_CrtDate[2] ;
+    unsigned char DIR_LstAccDate[2] ;
+    unsigned char DIR_FstClusHI[2] ;
+    unsigned char DIR_WrtTime[2] ;
+    unsigned char DIR_WrtDate[2];
+    unsigned char DIR_FstClusLO[2];
+    unsigned char DIR_FileSize[4] ;    
+};
+
+struct TLongDirEntry {
+    unsigned char LDIR_Ord ;
+    unsigned char LDIR_Name1[10] ;
+    unsigned char LDIR_Attr ;
+    unsigned char LDIR_Type ;
+    unsigned char LDIR_Chksum ;
+    unsigned char LDIR_Name2[12] ;
+    unsigned char LDIR_FstClusLO[2] ; 
+    unsigned char LDIR_Name3[4] ;
+};
+/* This class describes the attributes of a single directory/file/volume entry.
+ *
+ * @internalComponent
+ * @released
+ */
+class CDirectory
+{
+
+public:
+	FILESYSTEM_API CDirectory(const char* aEntryName,CDirectory* aParent);
+	FILESYSTEM_API ~CDirectory();
+	FILESYSTEM_API EntryList* GetEntryList();
+	FILESYSTEM_API void InsertIntoEntryList(CDirectory* aEntry);
+	FILESYSTEM_API void SetFilePath(char* aFilePath);
+	FILESYSTEM_API string GetFilePath() const;
+	FILESYSTEM_API void SetEntryName(string aEntryName);
+	FILESYSTEM_API string GetEntryName() const;
+	FILESYSTEM_API void SetEntryAttribute(char aAttribute);
+	FILESYSTEM_API char GetEntryAttribute() const;
+	char GetNtReservedByte() const;
+	char GetCreationTimeMsecs() const;
+	unsigned short int GetCreatedTime() const;
+	unsigned short int GetCreationDate() const;
+	unsigned short int GetLastAccessDate() const;
+	unsigned short int GetClusterNumberHi() const;
+	void SetClusterNumberHi(unsigned short int aHiClusterNumber);
+	unsigned short int GetClusterNumberLow() const;
+	void SetClusterNumberLow(unsigned short int aLowClusterNumber);
+	unsigned short int GetLastWriteDate() const;
+	unsigned short int GetLastWriteTime() const;
+	FILESYSTEM_API void SetFileSize(unsigned int aFileSize);
+	FILESYSTEM_API unsigned int GetFileSize() const;
+	bool IsFile() const ; 
+	FILESYSTEM_API CDirectory* GetParent()const {
+	    return iParent ;
+	}
+	FILESYSTEM_API bool GetShortEntry(TShortDirEntry& rEntry) ;
+	FILESYSTEM_API bool GetLongEntries(list<TLongDirEntry>& rEntries) ;
+private:
+	void InitializeTime();
+	void MakeUniqueShortName(unsigned char* rShortName,size_t aWavPos) const ;
+private:
+	string iEntryName;					//Directory or file name
+    unsigned char iShortName[12] ; 
+	char iAttribute;					//To mention file or directory or Volume
+	char iNtReserved;					//Reserved for use by windows NT, this value always zero
+	char iCreationTimeMsecs;			/**Millisecond stamp at file creation time, Since this is not 
+	so important, always initialized to zero*/
+	unsigned short int iCreatedTime;	//Time file was created
+	unsigned short int iCreationDate;	//Date file was created
+	unsigned short int iLastAccessDate;	//Date file was last accessed
+	unsigned short int iClusterNumberHi;//High word of this entry's first cluster number
+	unsigned short int iClusterNumberLow;//Low word of this entry's first cluster number
+	unsigned short int iLastWriteDate;	//Date file was written
+	unsigned short int iLastWriteTime;	//Time file was written
+	unsigned int iFileSize;				//file size
+	EntryList iDirectoryList;			//List Template used to hold subdirectories
+	
+	string iFilePath; //Holds file path only if the entry is of type "file"
+
+	struct tm* iDateAndTime;
+	union TTimeInteger iTime;
+	union TDateInteger iDate; 
+	CDirectory* iParent ;
+};
+
+#endif //DIRECTORY_H
--- a/imgtools/imglib/filesystem/include/dirregion.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/include/dirregion.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,94 +1,90 @@
-/*
-* 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: 
-* CDIRREGION.H
-* Directory Region Operations for FileSystem component
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef DIRREGION_H
-#define DIRREGION_H
-
-#include "filesystemclass.h"
-#include "longname.h"
-
-#include <fstream>
-#include <map>
-#include <string>
-
-class CFileSystem;
-
-typedef std::ofstream OfStream;
-typedef std::ifstream IfStream;
-typedef std::ios Ios;
-typedef std::map<unsigned int,std::string> StringMap;
-
-/**
-This class describes the member functions and data members required to create directory/data
-region of FAT image.
-
-@internalComponent
-@released
-*/
-
-class CDirRegion
-	{
-	private:
-		void FormatName(String& aString,char aAttrValue);
-		unsigned int Get32BitClusterNumber(unsigned int aHighWord, unsigned int aLowWord);
-		void CheckEntry(EntryList aNodeList);
-		void CreateDirEntry(CDirectory* aEntry,unsigned int aParentDirClusterNumber);
-		void CreateAndWriteCurrentDirEntry(unsigned int aCurClusterNumber,String& aString);
-		void CreateAndWriteParentDirEntry(unsigned int aParDirClusterNumber,String& aString);
-		void WriteEntryToString(CDirectory* aEntry,String& aString);
-		bool IsLongEntry(CDirectory* aEntry) const;
-		void CreateLongEntries(CDirectory* aEntry,String& aDirString);
-		void WriteFileDataInToCluster(CDirectory* aEntry); 
-		void PushStringIntoClusterMap(unsigned int aNumber, 
-									  String& aDirString,
-									  unsigned long int aClusterSize,
-									  char aAttribute);
-		void PushDirectoryEntryString(unsigned int aNumber,String& aString,int aClustersRequired);
-
-	public:
-		CDirRegion(	EntryList iNodeList,
-					CFileSystem *aFileSystemPtr);
-		~CDirRegion();
-		void Execute();
-		void WriteClustersIntoFile(OfStream& aOutPutStream);
-		TClustersPerEntryMap* GetClustersPerEntryMap() const;
-
-	private:
-		IfStream iInputStream; //Input stream, used to read file contents
-		CCluster* iClusterPtr; //pointer to class CCluster
-		bool iCurrentDirEntry; //Is current entry(.) is created?
-		bool iParentDirEntry;//Is parent entry (..) is created?
-		bool iFirstCluster; //Is this the first cluster for the current FAT image?
-
-		unsigned int iCurEntryClusterNumber; //Holds current entries cluster number
-		unsigned int iClusterKey; //Number used to map cluster with cluster contents
-		/* To avoid calling CCluster::GetClusterSize() function multiple times, this 
-		 *variable introduced.
-		 */
-		unsigned long int iClusterSize;
-		
-		StringMap iClusterMap; //The map between cluster number and cluster
-		unsigned int iRootDirSizeInBytes;//Reserved sectors for root directory entry
-		EntryList iNodeList;//To hold root directory entry
-	};
-
-#endif //DIRREGION_H
+/*
+* 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: 
+* CDIRREGION.H
+* Directory Region Operations for FileSystem component
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef DIRREGION_H
+#define DIRREGION_H
+
+#include "filesystemclass.h"
+#include "longname.h"
+
+#include <fstream>
+#include <map>
+#include <string>
+
+class CFileSystem;
+
+typedef ofstream OfStream;
+typedef ifstream IfStream;
+typedef ios Ios;
+typedef map<unsigned int,string> StringMap;
+
+/**
+This class describes the member functions and data members required to create directory/data
+region of FAT image.
+
+@internalComponent
+@released
+*/
+
+class CDirRegion
+	{
+	private: 
+		unsigned int Get32BitClusterNumber(unsigned int aHighWord, unsigned int aLowWord);
+		void CheckEntry(EntryList aNodeList);
+		void CreateDirEntry(CDirectory* aEntry,unsigned int aParentDirClusterNumber);
+		void CreateAndWriteCurrentDirEntry(unsigned int aCurClusterNumber,string& aString);
+		void CreateAndWriteParentDirEntry(unsigned int aParDirClusterNumber,string& aString); 
+		void WriteFileDataInToCluster(CDirectory* aEntry); 
+		void PushStringIntoClusterMap(unsigned int aNumber, 
+									  string& aDirString,
+									  unsigned long int aClusterSize,
+									  char aAttribute);
+		void PushDirectoryEntryString(unsigned int aNumber,string& aString,int aClustersRequired);
+
+	public:
+		CDirRegion(	EntryList iNodeList,
+					CFileSystem *aFileSystemPtr);
+		~CDirRegion();
+		void Execute();
+		void WriteClustersIntoFile(OfStream& aOutPutStream);
+		TClustersPerEntryMap* GetClustersPerEntryMap() const;
+
+	private:
+		IfStream iInputStream; //Input stream, used to read file contents
+		CCluster* iClusterPtr; //pointer to class CCluster
+		bool iCurrentDirEntry; //Is current entry(.) is created?
+		bool iParentDirEntry;//Is parent entry (..) is created?
+		bool iFirstCluster; //Is this the first cluster for the current FAT image?
+
+		unsigned int iCurEntryClusterNumber; //Holds current entries cluster number
+		unsigned int iClusterKey; //Number used to map cluster with cluster contents
+		/* To avoid calling CCluster::GetClusterSize() function multiple times, this 
+		 *variable introduced.
+		 */
+		unsigned long int iClusterSize;
+		
+		StringMap iClusterMap; //The map between cluster number and cluster
+		unsigned int iRootDirSizeInBytes;//Reserved sectors for root directory entry
+		EntryList iNodeList;//To hold root directory entry
+	};
+
+#endif //DIRREGION_H
--- a/imgtools/imglib/filesystem/include/errorhandler.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/include/errorhandler.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,51 +1,51 @@
-/*
-* 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: 
-* Error Handler Class for FileSystem component
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef ERRORHANDLER_H
-#define ERRORHANDLER_H
-
-#include "messagehandler.h"
-#include "constants.h"
-#include <iostream>
-#include <stdio.h>
-
-/**
-Class for Error handling
-
-@internalComponent
-@released
-*/
-class ErrorHandler
-{
-	public:
-		ErrorHandler(int aMessageIndex,char* aSubMessage,char* aFileName, int aLineNumber);
-        ErrorHandler(int aMessageIndex, char* aFileName, int aLineNumber);
-		virtual ~ErrorHandler();
-		void Report();
-
-		String iMessage;
-		int iMessageIndex;
-		String iSubMessage;
-        String iFileName;
-        int iLineNumber;
-};
-
-#endif //ERRORHANDLER_H
+/*
+* 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: 
+* Error Handler Class for FileSystem component
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef ERRORHANDLER_H
+#define ERRORHANDLER_H
+
+#include "messagehandler.h"
+#include "constants.h"
+#include <iostream>
+#include <stdio.h>
+
+/**
+Class for Error handling
+
+@internalComponent
+@released
+*/
+class ErrorHandler
+{
+	public:
+		ErrorHandler(int aMessageIndex,char* aSubMessage,char* aFileName, int aLineNumber);
+        ErrorHandler(int aMessageIndex, char* aFileName, int aLineNumber);
+		virtual ~ErrorHandler();
+		void Report();
+
+		string iMessage;
+		int iMessageIndex;
+		string iSubMessage;
+        string iFileName;
+        int iLineNumber;
+};
+
+#endif //ERRORHANDLER_H
--- a/imgtools/imglib/filesystem/include/fatbasebootsector.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/include/fatbasebootsector.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,113 +1,113 @@
-/*
-* 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: 
-* FAT base boot sector class for FileSystem component
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef FATBPBSECTOR_H
-#define FATBPBSECTOR_H
-
-#include "errorhandler.h"
-#include <string>
-#include <time.h>
-
-using namespace std;
-
-/**
-Class representing common fields of Boot Sector of all three fat system volume type.
-
-@internalComponent
-@released
-*/
-class TFATBaseBootSector
-
-{
-protected:
-	//jump instruction to boot code
-	unsigned char iJmpBoot[3];
-	unsigned char iOEMName[8] ;
-	unsigned short iBytesPerSector;
-	unsigned int  iHiddenSectors;
-	unsigned char iMedia; //Media Type
-	unsigned char iNumberOfFats;
-	unsigned short  iNumHeads; //number of heads for interrupt 0x13
-	unsigned short  iSectorsPerTrack; //sector per track for interrupt ox13
-	unsigned short iTotalSectors; //16 bit total count of sectors on the volume
-	unsigned int iTotalSectors32; //32 bit total count of sectors on the volume
-	unsigned char iPhysicalDriveNumber;
-	unsigned char iReservedByte;
-	unsigned char iBootSign; //extended boot signature
-	unsigned int  iVolumeId;
-	unsigned char iVolumeLabel[KMaxVolumeLabel];
-	unsigned short iRootDirEntries;
-	unsigned short iReservedSectors;
-	unsigned char  iSectorsPerCluster;
-	unsigned int  iFatSectors; //count of sectors occupied by FAT in FAT16 volume
-	unsigned int  iFatSectors32; //count of sectors occupied by FAT in FAT32 volume
-	unsigned char iFileSysType[KFileSysTypeLength];
-public:	
-	TFATBaseBootSector();
-	virtual ~TFATBaseBootSector();
-	//Get methods
-	unsigned char* JumpInstruction() ;
-	unsigned char* OEMName() ;
-	unsigned int BytesPerSector() const;
-	unsigned int FatSectors32() const;
-	unsigned short FatSectors() const;
-	unsigned char NumberOfFats() const;
-	unsigned short ReservedSectors() const;
-	unsigned short RootDirEntries() const;
-	unsigned char  SectorsPerCluster() const;
-	unsigned int TotalSectors(Long64 aPartitionSize) const;
-	unsigned short LowSectorsCount() const;
-	unsigned int HighSectorsCount() const;
-	unsigned char Media() const;
-	unsigned short SectorsPerTrack() const;
-	unsigned short NumberOfHeads() const;
-	unsigned int HiddenSectors() const;
-	unsigned char BootSectorDriveNumber() const;
-	unsigned char ReservedByte() const;
-	unsigned char BootSignature() const;
-	unsigned char* VolumeLab() ;
-	unsigned int VolumeId() const;
-	//utility functions
-	int Log2(int aNum);
-	//Set methods
-	void SetJumpInstruction();
-	void SetOEMName();
-	void SetBytesPerSector(unsigned int aDriveSectorSize);
-	void SetNumberOfFats(unsigned int aDriveNoOfFATs);
-	void ComputeTotalSectors(Long64 aPartitionSize);
-	void SetMedia();
-	void SetSectorsPerTrack();
-	void SetNumberOfHeads();
-	void SetHiddenSectors();
-	void SetBootSectorDriveNumber();
-	void SetReservedByte();
-	void SetBootSignature();
-	void SetVolumeId();
-	void SetVolumeLab(String aVolumeLable);
-	//virtual methods
-	virtual void SetRootDirEntries()=0;
-	virtual void SetFileSysType()=0;
-	virtual void SetReservedSectors()=0;
-	virtual void ComputeSectorsPerCluster(Long64 aPartitionSize)=0;
-	virtual void ComputeFatSectors(Long64 aPartitionSize)=0;	
-};
-
-#endif //FATBPBSECTOR_H
+/*
+* 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: 
+* FAT base boot sector class for FileSystem component
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef FATBPBSECTOR_H
+#define FATBPBSECTOR_H
+
+#include "errorhandler.h"
+#include <string>
+#include <time.h>
+
+using namespace std;
+
+/**
+Class representing common fields of Boot Sector of all three fat system volume type.
+
+@internalComponent
+@released
+*/
+class TFATBaseBootSector
+
+{
+protected:
+	//jump instruction to boot code
+	unsigned char iJmpBoot[3];
+	unsigned char iOEMName[8] ;
+	unsigned short iBytesPerSector;
+	unsigned int  iHiddenSectors;
+	unsigned char iMedia; //Media Type
+	unsigned char iNumberOfFats;
+	unsigned short  iNumHeads; //number of heads for interrupt 0x13
+	unsigned short  iSectorsPerTrack; //sector per track for interrupt ox13
+	unsigned short iTotalSectors; //16 bit total count of sectors on the volume
+	unsigned int iTotalSectors32; //32 bit total count of sectors on the volume
+	unsigned char iPhysicalDriveNumber;
+	unsigned char iReservedByte;
+	unsigned char iBootSign; //extended boot signature
+	unsigned int  iVolumeId;
+	unsigned char iVolumeLabel[KMaxVolumeLabel];
+	unsigned short iRootDirEntries;
+	unsigned short iReservedSectors;
+	unsigned char  iSectorsPerCluster;
+	unsigned int  iFatSectors; //count of sectors occupied by FAT in FAT16 volume
+	unsigned int  iFatSectors32; //count of sectors occupied by FAT in FAT32 volume
+	unsigned char iFileSysType[KFileSysTypeLength];
+public:	
+	TFATBaseBootSector();
+	virtual ~TFATBaseBootSector();
+	//Get methods
+	unsigned char* JumpInstruction() ;
+	unsigned char* OEMName() ;
+	unsigned int BytesPerSector() const;
+	unsigned int FatSectors32() const;
+	unsigned short FatSectors() const;
+	unsigned char NumberOfFats() const;
+	unsigned short ReservedSectors() const;
+	unsigned short RootDirEntries() const;
+	unsigned char  SectorsPerCluster() const;
+	unsigned int TotalSectors(Long64 aPartitionSize) const;
+	unsigned short LowSectorsCount() const;
+	unsigned int HighSectorsCount() const;
+	unsigned char Media() const;
+	unsigned short SectorsPerTrack() const;
+	unsigned short NumberOfHeads() const;
+	unsigned int HiddenSectors() const;
+	unsigned char BootSectorDriveNumber() const;
+	unsigned char ReservedByte() const;
+	unsigned char BootSignature() const;
+	unsigned char* VolumeLab() ;
+	unsigned int VolumeId() const;
+	//utility functions
+	int Log2(int aNum);
+	//Set methods
+	void SetJumpInstruction();
+	void SetOEMName();
+	void SetBytesPerSector(unsigned int aDriveSectorSize);
+	void SetNumberOfFats(unsigned int aDriveNoOfFATs);
+	void ComputeTotalSectors(Long64 aPartitionSize);
+	void SetMedia();
+	void SetSectorsPerTrack();
+	void SetNumberOfHeads();
+	void SetHiddenSectors();
+	void SetBootSectorDriveNumber();
+	void SetReservedByte();
+	void SetBootSignature();
+	void SetVolumeId();
+	void SetVolumeLab(string aVolumeLable);
+	//virtual methods
+	virtual void SetRootDirEntries()=0;
+	virtual void SetFileSysType()=0;
+	virtual void SetReservedSectors()=0;
+	virtual void ComputeSectorsPerCluster(Long64 aPartitionSize)=0;
+	virtual void ComputeFatSectors(Long64 aPartitionSize)=0;	
+};
+
+#endif //FATBPBSECTOR_H
--- a/imgtools/imglib/filesystem/include/filesysteminterface.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/include/filesysteminterface.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,91 +1,91 @@
-/*
-* 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: 
-* Interface class for FileSystem component
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef FILESYSTEMINTERFACE_H
-#define FILESYSTEMINTERFACE_H
-
-#include "directory.h"
-#include <fstream>
-
-typedef std::ofstream Ofstream;
-
-//default image size in Bytes
-const int KDefaultImageSize=50*1024*1024;
-
-//enum representing the file system type
-enum FILESYSTEM_API TFileSystem
-{
-	EFATINVALID=0,
-	EFAT12=1,
-	EFAT16,
-	EFAT32,
-	ELFFS
-};
-
-//error code return by the file system component
-enum TErrorCodes
-{
-	//File system not supported
-	EFSNotSupported = -1,
-	//File System general errors
-	EFileSystemError = EXIT_FAILURE
-};
-
-// Configurable FAT attributes
-struct ConfigurableFatAttributes
-{
-	String iDriveVolumeLabel;
-	unsigned int iDriveSectorSize;
-	unsigned int iDriveNoOfFATs;
-	
-	ConfigurableFatAttributes();
-};
-
-/**
-Interface class containing a static method exposed by the FileSystem 
-component to be used by an external tools
-
-@internalComponent
-@released
-
-@param aNodeList Directory structure 
-@param aFileSystem file system type
-@param aImageFileName image file name 
-@param aLogFileName log file name 
-@param aPartitionSize partition size in bytes
-*/
-
-class CFileSystemInterFace
-{
-private:
-		static Ofstream iOutputStream;
-public:
-		/**This method is exported to the external component to receive the information 
-		 * required by the FileSystem component
-		 */
-		static FILESYSTEM_API int CreateFilesystem(	EntryList* aNodeList ,TFileSystem aFileSystem, 
-													char* aImageFileName, 
-													char* aLogFileName,
-													ConfigurableFatAttributes* aConfigurableFatAttributes,
-													Long64 aPartitionSize=KDefaultImageSize); 
-};
-
-#endif //FILESYSTEMINTERFACE_H
+/*
+* 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: 
+* Interface class for FileSystem component
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef FILESYSTEMINTERFACE_H
+#define FILESYSTEMINTERFACE_H
+
+#include "directory.h"
+#include <fstream>
+
+typedef ofstream Ofstream;
+
+//default image size in Bytes
+const int KDefaultImageSize=50*1024*1024;
+
+//enum representing the file system type
+enum FILESYSTEM_API TFileSystem
+{
+	EFATINVALID=0,
+	EFAT12=1,
+	EFAT16,
+	EFAT32,
+	ELFFS
+};
+
+//error code return by the file system component
+enum TErrorCodes
+{
+	//File system not supported
+	EFSNotSupported = -1,
+	//File System general errors
+	EFileSystemError = EXIT_FAILURE
+};
+
+// Configurable FAT attributes
+struct ConfigurableFatAttributes
+{
+	string iDriveVolumeLabel;
+	unsigned int iDriveSectorSize;
+	unsigned int iDriveNoOfFATs;
+	
+	ConfigurableFatAttributes();
+};
+
+/**
+Interface class containing a static method exposed by the FileSystem 
+component to be used by an external tools
+
+@internalComponent
+@released
+
+@param aNodeList Directory structure 
+@param aFileSystem file system type
+@param aImageFileName image file name 
+@param aLogFileName log file name 
+@param aPartitionSize partition size in bytes
+*/
+
+class CFileSystemInterFace
+{
+private:
+		static Ofstream iOutputStream;
+public:
+		/**This method is exported to the external component to receive the information 
+		 * required by the FileSystem component
+		 */
+		static FILESYSTEM_API int CreateFilesystem(	EntryList* aNodeList ,TFileSystem aFileSystem, 
+													char* aImageFileName, 
+													char* aLogFileName,
+													ConfigurableFatAttributes* aConfigurableFatAttributes,
+													Long64 aPartitionSize=KDefaultImageSize); 
+};
+
+#endif //FILESYSTEMINTERFACE_H
--- a/imgtools/imglib/filesystem/include/longentry.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/include/longentry.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,71 +1,71 @@
-/*
-* 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: 
-* Long entry class for FileSystem component
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef LONGENTRY_H
-#define LONGENTRY_H
-
-/**
-This class is used to represents the single Long entry attributes.
-The long entry can be directory/file/volume entry.
-Also declares the functions to operate on them.
-
-@internalComponent
-@released
-*/
-#include "messagehandler.h"
-#include "directory.h"
-#include "constants.h"
-
-class CLongEntry
-{
-public:
-	char GetDirOrder() const;
-	void SetDirOrder(char aDirOrder);
-	String& GetSubName1();
-	void SetSubName1(String aSubName1);
-	String& GetSubName2();
-	void SetSubName2(String aSubName2);
-	String& GetSubName3();
-	void SetSubName3(String aSubName3);
-	char GetAttribute() const;
-	char GetCheckSum() const;
-	char GetDirType() const;
-	unsigned short int GetClusterNumberLow() const;
-
-private:
-	char iDirOrder;		//Order of this entry in the sequence of long directory entries
-	String iSubName1;	//character 1-5 of long name sub component
-	char iAttribute;	//LONG_FILE_NAME attribute
-	char iDirType;		//zero to mention subcomponent of directory entry
-	char iCheckSum;		//Check sum of Short directory entry name
-	String iSubName2;	//character 6-11 of long name sub component
-	/* Low of cluster number, must be zero for existing disk utility compatible 
-	 * reason
-	 */
-	unsigned short int iFirstClusterNumberLow;
-	String iSubName3;	//character 12-13 of long name sub component
-
-public:
-	CLongEntry(char aChckSum);
-	~CLongEntry();
-};
-
-#endif //LONGENTRY_H
+/*
+* 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: 
+* Long entry class for FileSystem component
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef LONGENTRY_H
+#define LONGENTRY_H
+
+/**
+This class is used to represents the single Long entry attributes.
+The long entry can be directory/file/volume entry.
+Also declares the functions to operate on them.
+
+@internalComponent
+@released
+*/
+#include "messagehandler.h"
+#include "directory.h"
+#include "constants.h"
+
+class CLongEntry
+{
+public:
+	char GetDirOrder() const;
+	void SetDirOrder(char aDirOrder);
+	string& GetSubName1();
+	void SetSubName1(string aSubName1);
+	string& GetSubName2();
+	void SetSubName2(string aSubName2);
+	string& GetSubName3();
+	void SetSubName3(string aSubName3);
+	char GetAttribute() const;
+	char GetCheckSum() const;
+	char GetDirType() const;
+	unsigned short int GetClusterNumberLow() const;
+
+private:
+	char iDirOrder;		//Order of this entry in the sequence of long directory entries
+	string iSubName1;	//character 1-5 of long name sub component
+	char iAttribute;	//LONG_FILE_NAME attribute
+	char iDirType;		//zero to mention subcomponent of directory entry
+	char iCheckSum;		//Check sum of Short directory entry name
+	string iSubName2;	//character 6-11 of long name sub component
+	/* Low of cluster number, must be zero for existing disk utility compatible 
+	 * reason
+	 */
+	unsigned short int iFirstClusterNumberLow;
+	string iSubName3;	//character 12-13 of long name sub component
+
+public:
+	CLongEntry(char aChckSum);
+	~CLongEntry();
+};
+
+#endif //LONGENTRY_H
--- a/imgtools/imglib/filesystem/include/longname.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/include/longname.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,103 +1,103 @@
-/*
-* 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: 
-* Long name class for FileSystem component
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef LONGNAME_H
-#define LONGNAME_H
-
-#include "cluster.h"
-#include "longentry.h"
-
-#define ToString(dataInteger) reinterpret_cast<char*>(&dataInteger),sizeof(dataInteger)
-
-typedef std::stack<CLongEntry*> LongEntryStack;
-typedef std::list<String> StringList;
-
-//Long entry sub name lengths
-enum TLongSubNameLength
-{
-	ESubName1Length = 5,
-	ESubName2Length = 6,
-	ESubName3Length = 2
-};
-
-//Name length constants
-enum TNameLength
-{
-	EExtensionLength = 0x03,
-	EShortNameInitialLength = 0x06,
-	ETildeNumberPosition = 0x07,
-	ENameLength = 0x8,
-	ENameLengthWithExtension = 0x0B
-};
-
-//Holds all the short directory entry.
-static StringList GShortEntryList;
-
-/**
-This class is used to prepare Long Name Directory entry portion of Directory Entry region
-
-@internalComponent
-@released
-*/
-class ClongName
-{
-private:
-	StringList iSubNamesList;		//Holds the splitted file names 
-	LongEntryStack iLongEntryStack;	//Holds all the long name directory entry node's
-	unsigned int iClusterNumber;	//Current cluster number, where the current long entry needs to be written
-	CCluster* iClusterPtr;
-	String iLongName;
-	char iLongEntryAttribute;
-	String iShortName;
-	unsigned int iLongNameLength;
-	unsigned int iTildeNumberPosition;
-	/**If the received sub name entry size is equal to its expected length, then
-	two NULL character should be preceded at the start of next sub name 
-	*/
-	bool iSubNameProperEnd; //Is name ends without NULL character termination?
-	bool iFirstNullName;// Is first name ending with NULL character?
-
-private:
-	String GetShortEntryName();
-	unsigned char CalculateCheckSum();
-	void WriteLongEntry(CLongEntry* aLongEntry,String& longEntryString);
-	void WriteSubName(String& aSubName,unsigned short aSubNameLength,
-					  String& alongEntryString);
-	void FormatLongFileName(String& aLongName);
-	void CheckAndUpdateShortName(String& aShortName);
-	void PushAndErase(String& aFirstName,String& aSecondName,String& aThirdName);
-	void GetSubName(String& aLongName,
-				   int& aStartIndex,
-				   int& aStringLength,
-				   int aSubNameLength,
-				   String& aSubName);
-	void PopAndErase();
-	void CalculateExtentionLength();
-
-public:
-	ClongName(CCluster* aClusterPtr, CDirectory* aEntry);
-	~ClongName();
-	CDirectory* CreateShortEntry(CDirectory* aEntry);
-	String CreateLongEntries();
-	static void DestroyShortEntryList();
-};
-
-#endif //LONGNAME_H
+/*
+* 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: 
+* Long name class for FileSystem component
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef LONGNAME_H
+#define LONGNAME_H
+
+#include "cluster.h"
+#include "longentry.h"
+
+#define ToString(dataInteger) reinterpret_cast<char*>(&dataInteger),sizeof(dataInteger)
+
+typedef stack<CLongEntry*> LongEntryStack;
+typedef list<string> StringList;
+
+//Long entry sub name lengths
+enum TLongSubNameLength
+{
+	ESubName1Length = 5,
+	ESubName2Length = 6,
+	ESubName3Length = 2
+};
+
+//Name length constants
+enum TNameLength
+{
+	EExtensionLength = 0x03,
+	EShortNameInitialLength = 0x06,
+	ETildeNumberPosition = 0x07,
+	ENameLength = 0x8,
+	ENameLengthWithExtension = 0x0B
+};
+
+//Holds all the short directory entry.
+static StringList GShortEntryList;
+
+/**
+This class is used to prepare Long Name Directory entry portion of Directory Entry region
+
+@internalComponent
+@released
+*/
+class ClongName
+{
+private:
+	StringList iSubNamesList;		//Holds the splitted file names 
+	LongEntryStack iLongEntryStack;	//Holds all the long name directory entry node's
+	unsigned int iClusterNumber;	//Current cluster number, where the current long entry needs to be written
+	CCluster* iClusterPtr;
+	string iLongName;
+	char iLongEntryAttribute;
+	string iShortName;
+	unsigned int iLongNameLength;
+	unsigned int iTildeNumberPosition;
+	/**If the received sub name entry size is equal to its expected length, then
+	two NULL character should be preceded at the start of next sub name 
+	*/
+	bool iSubNameProperEnd; //Is name ends without NULL character termination?
+	bool iFirstNullName;// Is first name ending with NULL character?
+
+private:
+	string GetShortEntryName();
+	unsigned char CalculateCheckSum();
+	void WriteLongEntry(CLongEntry* aLongEntry,string& longEntryString);
+	void WriteSubName(string& aSubName,unsigned short aSubNameLength,
+					  string& alongEntryString);
+	void FormatLongFileName(string& aLongName);
+	void CheckAndUpdateShortName(string& aShortName);
+	void PushAndErase(string& aFirstName,string& aSecondName,string& aThirdName);
+	void GetSubName(string& aLongName,
+				   int& aStartIndex,
+				   int& aStringLength,
+				   int aSubNameLength,
+				   string& aSubName);
+	void PopAndErase();
+	void CalculateExtentionLength();
+
+public:
+	ClongName(CCluster* aClusterPtr, CDirectory* aEntry);
+	~ClongName();
+	CDirectory* CreateShortEntry(CDirectory* aEntry);
+	string CreateLongEntries();
+	static void DestroyShortEntryList();
+};
+
+#endif //LONGNAME_H
--- a/imgtools/imglib/filesystem/include/messageimplementation.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/include/messageimplementation.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,131 +1,125 @@
-/*
-* 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: 
-* Message Implementation Class for FileSystem tool
-* @internalComponent
-* @released
-*
-*/
-
-
-
-#ifndef MESSAGEIMPLEMENTATION_H
-#define MESSAGEIMPLEMENTATION_H
-
-#ifdef _MSC_VER 
-	#pragma warning(disable: 4514) // unreferenced inline function has been removed
-	#pragma warning(disable: 4702) // unreachable code
-	#pragma warning(disable: 4710) // function not inlined
-	#pragma warning(disable: 4786) // identifier was truncated to '255' characters in the debug information
-	#pragma warning(disable: 4103) // used #pragma pack to change alignment
-#endif
-
-#include <map>
-#include <string>
-#include <stdarg.h>
-
-typedef std::map<int,char*> Map;
-typedef std::string String;
-
-enum 
-{ 
-	ERROR = 0,
-	WARNING,
-	INFORMATION
-};
-/**
-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 size by number of messages included
-*/
-enum 
-{	FILEOPENERROR = 1,
-	FILEREADERROR,
-	FILEWRITEERROR,
-	MEMORYALLOCATIONERROR,
-	ENTRYCREATEMSG,
-	BOOTSECTORERROR,
-	BOOTSECTORCREATEMSG,
-	BOOTSECTORWRITEMSG,
-	FATTABLEWRITEMSG,
-	IMAGESIZETOOBIG,
-	NOENTRIESFOUND,
-	EMPTYFILENAME,
-	EMPTYSHORTNAMEERROR,
-	CLUSTERERROR,
-	ROOTNOTFOUND,
-	UNKNOWNERROR
-};
-
-
-/**
-Abstract base Class for Message Implementation.
-
-@internalComponent
-@released
-*/
-class Message
-{
-    public:
-		virtual ~Message(){};
-		// get error string from message file
-		virtual char * GetMessageString(int errorIndex)=0;
-		// display message to output device
-		virtual void Output(const char *aName) =0;
-		// start logging to a file
-		virtual void StartLogging(char *fileName)=0;
-		virtual void ReportMessage(int aMsgType, int aMsgIndex,...)=0;
-		virtual void InitializeMessages()=0;
-};
-
-/**
-Class for Message Implementation.
-
-@internalComponent
-@released
-*/
-class MessageImplementation : public Message
-{
-    public:
-		MessageImplementation();
-		~MessageImplementation();
-
-		//override base class methods
-		char* GetMessageString(int errorIndex);
-		void Output(const char *aName);
-		void LogOutput(const char *aString);
-		void StartLogging(char *fileName);
-		void ReportMessage(int aMsgType, int aMsgIndex,...);
-		void InitializeMessages();
-    private:
-
-		bool iLogging;
-		char* iLogFileName;
-		FILE *iLogPtr;
-		Map iMessage;
-};
-
-/**
-Structure for Messages.
-
-@internalComponent
-@released
-*/
-struct EnglishMessage
-{
-	int index;
-	char message[1024];
-};
-
-#endif //MESSAGEIMPLEMENTATION_H
+/*
+* 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: 
+* Message Implementation Class for FileSystem tool
+* @internalComponent
+* @released
+*
+*/
+
+
+
+#ifndef MESSAGEIMPLEMENTATION_H
+#define MESSAGEIMPLEMENTATION_H
+
+ 
+
+#include <map>
+#include <string>
+#include <stdarg.h>
+using namespace std;
+typedef map<int,char*> Map;
+ 
+
+enum 
+{ 
+	ERROR = 0,
+	WARNING,
+	INFORMATION
+};
+/**
+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 size by number of messages included
+*/
+enum 
+{	FILEOPENERROR = 1,
+	FILEREADERROR,
+	FILEWRITEERROR,
+	MEMORYALLOCATIONERROR,
+	ENTRYCREATEMSG,
+	BOOTSECTORERROR,
+	BOOTSECTORCREATEMSG,
+	BOOTSECTORWRITEMSG,
+	FATTABLEWRITEMSG,
+	IMAGESIZETOOBIG,
+	NOENTRIESFOUND,
+	EMPTYFILENAME,
+	EMPTYSHORTNAMEERROR,
+	CLUSTERERROR,
+	ROOTNOTFOUND,
+	UNKNOWNERROR
+};
+
+
+/**
+Abstract base Class for Message Implementation.
+
+@internalComponent
+@released
+*/
+class Message
+{
+    public:
+		virtual ~Message(){};
+		// get error string from message file
+		virtual char * GetMessageString(int errorIndex)=0;
+		// display message to output device
+		virtual void Output(const char *aName) =0;
+		// start logging to a file
+		virtual void StartLogging(char *fileName)=0;
+		virtual void ReportMessage(int aMsgType, int aMsgIndex,...)=0;
+		virtual void InitializeMessages()=0;
+};
+
+/**
+Class for Message Implementation.
+
+@internalComponent
+@released
+*/
+class MessageImplementation : public Message
+{
+    public:
+		MessageImplementation();
+		~MessageImplementation();
+
+		//override base class methods
+		char* GetMessageString(int errorIndex);
+		void Output(const char *aName);
+		void LogOutput(const char *aString);
+		void StartLogging(char *fileName);
+		void ReportMessage(int aMsgType, int aMsgIndex,...);
+		void InitializeMessages();
+    private:
+
+		bool iLogging;
+		char* iLogFileName;
+		FILE *iLogPtr;
+		Map iMessage;
+};
+
+/**
+Structure for Messages.
+
+@internalComponent
+@released
+*/
+struct EnglishMessage
+{
+	int index;
+	char message[1024];
+};
+
+#endif //MESSAGEIMPLEMENTATION_H
--- a/imgtools/imglib/filesystem/include/utils.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/include/utils.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,66 +1,66 @@
-/*
-* 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: 
-* UTILSH
-* Contains common utilitied required for filesystem component.
-* @internalComponent
-* @released
-*
-*/
-
-
-#ifndef UTILS_H
-#define UTILS_H
-
-#include <string>
-
-/* While generating FAT32 image, user may specify the larger partition size (say 128GB),
- * Hence to support large integer values 64 bit integers are used.
- * "__int64" is for MSVC compiler and "long long int" is for GCC compilers
- */
-#ifdef _MSC_VER
-	typedef __int64 Long64;
-#else
-	typedef long long int Long64;
-#endif
-
-typedef std::string String;
-
-/**
-Function responsible to convert given string into upper case.
-Note: In FAT iamge regular entry names are need to be mentioned in Upper case.
-
-@internalComponent
-@released
-
-@param aString - input string 
-@return returns the string, were string alphabets are changed to uppercase
-*/
-inline String& ToUpper(String& aString)
-{
-	unsigned int stringLength = aString.length();
-	for(unsigned int stringIndex = 0; stringIndex < stringLength; stringIndex++)
-	{
-		unsigned char stringChar = aString.at(stringIndex);
-		//Lower case alphabets ASCII value used here, 97 is for 'a' 122 is for 'z'
-		if( stringChar >= 97 && stringChar <= 122 )
-		{
-			stringChar -= 32; //Lower case alphabets case changed to upper case
-		}
-		aString[stringIndex] = stringChar;
-	}
-	return aString;
-}
-
-#endif //UTILS_H
+/*
+* 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: 
+* UTILSH
+* Contains common utilitied required for filesystem component.
+* @internalComponent
+* @released
+*
+*/
+
+
+#ifndef UTILS_H
+#define UTILS_H
+
+#include <string>
+
+/* While generating FAT32 image, user may specify the larger partition size (say 128GB),
+ * Hence to support large integer values 64 bit integers are used.
+ * "__int64" is for MSVC compiler and "long long int" is for GCC compilers
+ */
+#ifdef _MSC_VER
+	typedef __int64 Long64;
+#else
+	typedef long long int Long64;
+#endif
+
+using namespace std;
+
+/**
+Function responsible to convert given string into upper case.
+Note: In FAT iamge regular entry names are need to be mentioned in Upper case.
+
+@internalComponent
+@released
+
+@param aString - input string 
+@return returns the string, were string alphabets are changed to uppercase
+*/
+inline string& ToUpper(string& aString)
+{
+	unsigned int stringLength = aString.length();
+	for(unsigned int stringIndex = 0; stringIndex < stringLength; stringIndex++)
+	{
+		unsigned char stringChar = aString.at(stringIndex);
+		//Lower case alphabets ASCII value used here, 97 is for 'a' 122 is for 'z'
+		if( stringChar >= 97 && stringChar <= 122 )
+		{
+			stringChar -= 32; //Lower case alphabets case changed to upper case
+		}
+		aString[stringIndex] = stringChar;
+	}
+	return aString;
+}
+
+#endif //UTILS_H
--- a/imgtools/imglib/filesystem/source/cluster.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/source/cluster.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,191 +1,191 @@
-/*
-* 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: 
-* Cluster class used to allocate cluster numbers for directory entries 
-* and while writing file contents. And it is responsible to create the 
-* MAP of content starting cluster to ending cluster which can be used 
-* to generate FAT table. Since the cluster number is unique all over the
-* filesystem component, this class is designed as singleton class.
-* @internalComponent
-* @released
-*
-*/
-
-
-#include "cluster.h"
-
-
-//Initialize the Static CCluster instance pointer
-CCluster* CCluster::iClusterInstance = NULL;
-
-/**
-Static function which is used to instantiate and return the address of CCluster class.
-
-@internalComponent
-@released
-
-@param aClusterSize - single cluster size in Bytes
-@param aTotalNumberOfClusters - Maximum number of clusters
-@return - returns the instance of CCluster class
-*/
-
-CCluster* CCluster::Instance(unsigned int aClusterSize,unsigned int aTotalNumberOfClusters) 
-{
-	if (iClusterInstance == NULL)  // is it the first call?
-    {  
-		// create sole instance
-		iClusterInstance = new CCluster(aClusterSize, aTotalNumberOfClusters);
-    }
-    return iClusterInstance; // address of sole instance
-}
-
-/**
-Destructor: Clears the clusters per entry map
-
-@internalComponent
-@released
-*/
-CCluster::~CCluster ()
-{
-	iClustersPerEntry.clear();
-	iClusterInstance = NULL;
-}
-
-
-/**
-Constructor Receives inputs from dirregion Class and initializes the class variables
-
-@internalComponent
-@released
-
-@param aClusterSize - Size of every Cluster
-@param aTotalNumberOfClusters - maximum number of clusters allowed for current FAT image
-*/
-CCluster::CCluster(unsigned int aClusterSize, unsigned int aTotalNumberOfClusters)
-				   :iClusterSize(aClusterSize),iTotalNumberOfClusters(aTotalNumberOfClusters)
-{
-	iRootClusterNumber = KRootClusterNumber;
-	iCurrentClusterNumber = iRootClusterNumber;
-}
-
-/**
-Function to return the current cluster number
-
-@internalComponent
-@released
-
-@return - returns the current cluster number
-*/
-unsigned int CCluster::GetCurrentClusterNumber() const
-{
-	return iCurrentClusterNumber;
-}
-
-/** 
-Function to decrement the current cluster number
-
-@internalComponent
-@released
-*/
-void CCluster::DecrementCurrentClusterNumber()
-{
-	--iCurrentClusterNumber;
-}
-
-/**
-Function to get the High word of Current cluster number
-
-@internalComponent
-@released
-
-@return - returns the 16 bit HIGH word
-*/
-unsigned short int CCluster::GetHighWordClusterNumber() const
-{
-	return (unsigned short)(iCurrentClusterNumber >> KBitShift16);
-}
-
-/**
-Function to get the Low word of Current cluster number
-
-@internalComponent
-@released
-
-@return - returns the 16 bit LOW word
-*/
-unsigned short int CCluster::GetLowWordClusterNumber() const
-{
-	return (unsigned short)(iCurrentClusterNumber & KHighWordMask);
-}
-
-
-/**
-Function responsible to 
-1. Increment the current Cluster Number 
-2. Throw the error "image size too big" if the allocated clusters count exceeds total
-number of available clusters.
-
-@internalComponent
-@released
-*/
-void CCluster::UpdateNextAvailableClusterNumber()
-{
-	if(iCurrentClusterNumber >= iTotalNumberOfClusters)
-	{
-    	throw ErrorHandler(IMAGESIZETOOBIG,"Occupied number of clusters count exceeded than available clusters",__FILE__,__LINE__);
-	}
-	++iCurrentClusterNumber;
-}
-
-/**
-Function to Return the cluster size
-
-@internalComponent
-@released
-
-@return the cluster size
-*/
-unsigned int CCluster::GetClusterSize() const
-{
-	return iClusterSize;
-}
-
-/**
-Function Creates mapping between starting cluster number (where data starts) and 
-the sub sequent cluster numbers (where the data extends).
-
-@internalComponent
-@released
-
-@param aStartingClusterNumber - Cluster number where the data starts
-@param aPairClusterNumber - Cluster number where the data extends
-*/
-void CCluster::CreateMap(unsigned int aStartingClusterNumber,unsigned int aPairClusterNumber)
-{
-	iClustersPerEntry.insert(std::make_pair(aStartingClusterNumber,aPairClusterNumber));
-}
-
-/**
-Function to get Clusters per Entry MAP container.
-
-@internalComponent
-@released
-
-@return - returns the CLusters per entry container
-*/
-
-TClustersPerEntryMap* CCluster::GetClustersPerEntryMap()
-{
-	return &iClustersPerEntry;
-}
+/*
+* 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: 
+* Cluster class used to allocate cluster numbers for directory entries 
+* and while writing file contents. And it is responsible to create the 
+* MAP of content starting cluster to ending cluster which can be used 
+* to generate FAT table. Since the cluster number is unique all over the
+* filesystem component, this class is designed as singleton class.
+* @internalComponent
+* @released
+*
+*/
+
+
+#include "cluster.h"
+
+
+//Initialize the Static CCluster instance pointer
+CCluster* CCluster::iClusterInstance = NULL;
+
+/**
+Static function which is used to instantiate and return the address of CCluster class.
+
+@internalComponent
+@released
+
+@param aClusterSize - single cluster size in Bytes
+@param aTotalNumberOfClusters - Maximum number of clusters
+@return - returns the instance of CCluster class
+*/
+
+CCluster* CCluster::Instance(unsigned int aClusterSize,unsigned int aTotalNumberOfClusters) 
+{
+	if (iClusterInstance == NULL)  // is it the first call?
+    {  
+		// create sole instance
+		iClusterInstance = new CCluster(aClusterSize, aTotalNumberOfClusters);
+    }
+    return iClusterInstance; // address of sole instance
+}
+
+/**
+Destructor: Clears the clusters per entry map
+
+@internalComponent
+@released
+*/
+CCluster::~CCluster ()
+{
+	iClustersPerEntry.clear();
+	iClusterInstance = NULL;
+}
+
+
+/**
+Constructor Receives inputs from dirregion Class and initializes the class variables
+
+@internalComponent
+@released
+
+@param aClusterSize - Size of every Cluster
+@param aTotalNumberOfClusters - maximum number of clusters allowed for current FAT image
+*/
+CCluster::CCluster(unsigned int aClusterSize, unsigned int aTotalNumberOfClusters)
+				   :iClusterSize(aClusterSize),iTotalNumberOfClusters(aTotalNumberOfClusters)
+{
+	iRootClusterNumber = KRootClusterNumber;
+	iCurrentClusterNumber = iRootClusterNumber;
+}
+
+/**
+Function to return the current cluster number
+
+@internalComponent
+@released
+
+@return - returns the current cluster number
+*/
+unsigned int CCluster::GetCurrentClusterNumber() const
+{
+	return iCurrentClusterNumber;
+}
+
+/** 
+Function to decrement the current cluster number
+
+@internalComponent
+@released
+*/
+void CCluster::DecrementCurrentClusterNumber()
+{
+	--iCurrentClusterNumber;
+}
+
+/**
+Function to get the High word of Current cluster number
+
+@internalComponent
+@released
+
+@return - returns the 16 bit HIGH word
+*/
+unsigned short int CCluster::GetHighWordClusterNumber() const
+{
+	return (unsigned short)(iCurrentClusterNumber >> KBitShift16);
+}
+
+/**
+Function to get the Low word of Current cluster number
+
+@internalComponent
+@released
+
+@return - returns the 16 bit LOW word
+*/
+unsigned short int CCluster::GetLowWordClusterNumber() const
+{
+	return (unsigned short)(iCurrentClusterNumber & KHighWordMask);
+}
+
+
+/**
+Function responsible to 
+1. Increment the current Cluster Number 
+2. Throw the error "image size too big" if the allocated clusters count exceeds total
+number of available clusters.
+
+@internalComponent
+@released
+*/
+void CCluster::UpdateNextAvailableClusterNumber()
+{
+	if(iCurrentClusterNumber >= iTotalNumberOfClusters)
+	{
+    	throw ErrorHandler(IMAGESIZETOOBIG,"Occupied number of clusters count exceeded than available clusters",__FILE__,__LINE__);
+	}
+	++iCurrentClusterNumber;
+}
+
+/**
+Function to Return the cluster size
+
+@internalComponent
+@released
+
+@return the cluster size
+*/
+unsigned int CCluster::GetClusterSize() const
+{
+	return iClusterSize;
+}
+
+/**
+Function Creates mapping between starting cluster number (where data starts) and 
+the sub sequent cluster numbers (where the data extends).
+
+@internalComponent
+@released
+
+@param aStartingClusterNumber - Cluster number where the data starts
+@param aPairClusterNumber - Cluster number where the data extends
+*/
+void CCluster::CreateMap(unsigned int aStartingClusterNumber,unsigned int aPairClusterNumber)
+{
+	iClustersPerEntry.insert(make_pair(aStartingClusterNumber,aPairClusterNumber));
+}
+
+/**
+Function to get Clusters per Entry MAP container.
+
+@internalComponent
+@released
+
+@return - returns the CLusters per entry container
+*/
+
+TClustersPerEntryMap* CCluster::GetClustersPerEntryMap()
+{
+	return &iClustersPerEntry;
+}
--- a/imgtools/imglib/filesystem/source/directory.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/source/directory.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,385 +1,550 @@
-/*
-* 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: 
-* Directory class exports the functions required to construct either 
-* single entry (constructor) or to construct directory structure.
-* Also initializes the date and time attributes for all newly created
-* entries.
-* @internalComponent
-* @released
-*
-*/
-
-
-#include "errorhandler.h"
-#include "directory.h"
-#include "constants.h"
-
-/**
-Constructor:
-1. To Initialize the date and time variable
-2. Also to initialize other variable's
-
-@internalComponent
-@released
-
-@param aEntryName - the entry name
-*/
-
-FILESYSTEM_API CDirectory::CDirectory(char* aEntryName):
-						iEntryName(aEntryName),
-						iAttribute(0),
-						iNtReserved(KNTReserverdByte),
-						iCreationTimeMsecs(KCreateTimeInMsecs),
-						iClusterNumberHi(0),
-						iClusterNumberLow(0),
-						iFileSize (0) 
-{
-	InitializeTime();
-}
-
-/**
-Destructor: 
-1. To delete all the entries available in the form of directory structure
-2. Also to delete the current entry
-
-@internalComponent
-@released 
-*/
-
-FILESYSTEM_API CDirectory::~CDirectory()
-{
-	while(iDirectoryList.size() > 0)
-	{
-		delete iDirectoryList.front();
-		iDirectoryList.pop_front();
-	}
-}
-
-/**
-Function to initialize the time attributes of an entry
-
-@internalComponent
-@released 
-*/
-
-void CDirectory::InitializeTime()
-{
-	time_t rawtime;
-	time ( &rawtime );
-	iDateAndTime = localtime ( &rawtime );
-	iDate.iCurrentDate.Day = iDateAndTime->tm_mday;
-	iDate.iCurrentDate.Month = iDateAndTime->tm_mon+1; //As per FAT spec
-	iDate.iCurrentDate.Year = iDateAndTime->tm_year - 80;//As per FAT spec
-	iTime.iCurrentTime.Hour = iDateAndTime->tm_hour;
-	iTime.iCurrentTime.Minute = iDateAndTime->tm_min;
-	iTime.iCurrentTime.Seconds = iDateAndTime->tm_sec / 2;//As per FAT spec
-
-	iCreationDate = iDate.iImageDate;
-	iCreatedTime = iTime.iImageTime;
-	iLastAccessDate = iDate.iImageDate;
-	iLastWriteDate = iDate.iImageDate;
-	iLastWriteTime = iTime.iImageTime;
-}
-
-/**
-Function to initialize the entry name
-
-@internalComponent
-@released
-
-@param aEntryName - entry name need to be initialized
-*/
-FILESYSTEM_API void CDirectory::SetEntryName(String aEntryName)
-{
-	iEntryName = aEntryName;
-}
-
-/**
-Function to return the entry name
-
-@internalComponent
-@released
-
-@return iEntryName - the entry name
-*/
-
-FILESYSTEM_API String CDirectory::GetEntryName() const
-{
-	return iEntryName;
-}
-
-/**
-Function to initialize the file path
-
-@internalComponent
-@released
-
-@param aFilePath - where the current entry contents actually stored
-*/
-FILESYSTEM_API void CDirectory::SetFilePath(char* aFilePath)
-{
-	iFilePath.assign(aFilePath);
-}
-
-/**
-Function to return the file path
-
-@internalComponent
-@released
-
-@return iFilePath - the file path
-*/
-FILESYSTEM_API String CDirectory::GetFilePath() const
-{
-	return iFilePath;
-}
-
-/**
-Function to set the entry attribute
-
-@internalComponent
-@released
-
-@param aAttribute - entry attribute
-*/
-FILESYSTEM_API void CDirectory::SetEntryAttribute(char aAttribute)
-{
-	iAttribute = aAttribute;
-}
-
-/**
-Function to return the entry attribute
-
-@internalComponent
-@released
-
-@return iAttribute - the entry attribute
-*/
-FILESYSTEM_API char CDirectory::GetEntryAttribute() const
-{
-	return iAttribute;
-}
-
-
-/**
-Function to initialize the file size, this function is called only if the entry is of
-type File.
-
-@internalComponent
-@released
-
-@param aFileSize - the current entry file size
-*/
-FILESYSTEM_API void CDirectory::SetFileSize(unsigned int aFileSize)
-{
-	iFileSize = aFileSize;
-}
-
-/**
-Function to return the entry file size, this function is called only if the entry is of
-type File.
-
-@internalComponent
-@released
-
-@return iFileSize - the file size
-*/
-FILESYSTEM_API unsigned int CDirectory::GetFileSize() const
-{
-	return iFileSize;
-}
-
-/**
-Function to check whether this is a file 
-
-@internalComponent
-@released 
-
-@return iFileFlag - the File Flag
-*/
-bool CDirectory::IsFile() const 
-{
-	return (iAttribute & EAttrDirectory) == 0  ;
-}
-
-/**
-Function to return the entries Nt Reserved byte
-
-@internalComponent
-@released 
-
-@return iNtReserverd - the Nt Reserved byte
-*/
-char CDirectory::GetNtReservedByte() const
-{
-	return iNtReserved;
-}
-
-/**
-Function to return the entry Creation time in milli-seconds.
-
-@internalComponent
-@released
-
-@return iCreatedTimeMsecs - created time in Milli-seconds
-*/
-char CDirectory::GetCreationTimeMsecs() const
-{
-	return iCreationTimeMsecs;
-}
-
-/**
-Function to return the entry Created time
-
-@internalComponent
-@released
-
-@retun iCreatedTime - created time
-*/
-unsigned short int CDirectory::GetCreatedTime() const
-{
-	return iCreatedTime;
-}
-
-/**
-Function to return the entry Created date
-
-@internalComponent
-@released
-
-@return iCreationDate - created date
-*/
-unsigned short int CDirectory::GetCreationDate() const
-{
-	return iCreationDate;
-}
-
-/**
-Function to return the entry last accessed date
-
-@internalComponent
-@released
-
-@return iLastAccessDate - last access date
-*/
-unsigned short int CDirectory::GetLastAccessDate() const
-{
-	return iLastAccessDate;
-}
-
-/**
-Function to set high word cluster number
-
-@internalComponent
-@released
-
-@param aHiClusterNumber - high word of current cluster number
-*/
-void CDirectory::SetClusterNumberHi(unsigned short int aHiClusterNumber)
-{
-	iClusterNumberHi = aHiClusterNumber;
-}
-
-/**
-Function to return high word cluster number
-
-@internalComponent
-@released
-
-@return iClusterNumberHi - high word of cluster number
-*/
-unsigned short int CDirectory::GetClusterNumberHi() const
-{
-	return iClusterNumberHi;
-}
-
-/**
-Function to set low word cluster number
-
-@internalComponent
-@released 
-
-@param aLowClusterNumber - low word of current cluster number
-*/
-void CDirectory::SetClusterNumberLow(unsigned short int aLowClusterNumber)
-{
-	iClusterNumberLow = aLowClusterNumber;
-}
-
-/**
-Function to return low word cluster number
-
-@internalComponent
-@released 
-
-@return iClusterNumberLow - low word of cluster number
-*/
-unsigned short int CDirectory::GetClusterNumberLow() const
-{
-	return iClusterNumberLow;
-}
-
-/**
-Function to return last write date
-
-@internalComponent
-@released 
-
-@return iLastWriteDate - last write date
-*/
-unsigned short int CDirectory::GetLastWriteDate() const
-{
-	return iLastWriteDate;
-}
-
-/**
-Function to return last write time
-
-@internalComponent
-@released
-
-@return iLastWriteTime - last write time
-*/
-unsigned short int CDirectory::GetLastWriteTime() const
-{
-	return iLastWriteTime;
-}
-
-/**
-Function to return sub directory/file list
-
-@internalComponent
-@released
-
-@return iDirectoryList -  entry list
-*/
-FILESYSTEM_API EntryList* CDirectory::GetEntryList()
-{
-	return &iDirectoryList;
-}
-
-/**
-Function to insert a entry into Directory list. Also this function can be used 
-extensively to construct tree form of directory structure.
-
-@internalComponent
-@released
-
-@param aEntry - the entry to be inserted
-*/
-FILESYSTEM_API void CDirectory::InsertIntoEntryList(CDirectory* aEntry)
-{
-	iDirectoryList.push_back(aEntry);
-}
+/*
+* 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: 
+* Directory class exports the functions required to construct either 
+* single entry (constructor) or to construct directory structure.
+* Also initializes the date and time attributes for all newly created
+* entries.
+* @internalComponent
+* @released
+*
+*/
+
+
+#include "errorhandler.h"
+#include "directory.h"
+#include "constants.h"
+#include "utf16string.h"
+/**
+Constructor:
+1. To Initialize the date and time variable
+2. Also to initialize other variable's
+
+@internalComponent
+@released
+
+@param aEntryName - the entry name
+*/
+
+FILESYSTEM_API CDirectory::CDirectory(const char* aEntryName,CDirectory* aParent):
+						iEntryName(aEntryName),
+						iAttribute(0),
+						iNtReserved(KNTReserverdByte),
+						iCreationTimeMsecs(KCreateTimeInMsecs),
+						iClusterNumberHi(0),
+						iClusterNumberLow(0),
+						iFileSize (0), 
+						iParent(aParent) 
+{
+	InitializeTime();
+	
+	memset(iShortName,0x20,11);
+	iShortName[11] = 0 ; 
+	size_t length = iEntryName.length();
+	if(0 == length)
+	    return ;
+	if(0 == strcmp(aEntryName,".")){
+        iShortName[0] = '.' ;
+        return ;
+	}
+	if(0 == strcmp(aEntryName,"..")){
+        iShortName[0] = '.' ;
+        iShortName[1] = '.' ;
+        return ;
+    }
+    size_t lenOfSuffix = 0 ;
+    size_t dotPos = iEntryName.rfind('.',length);
+    size_t lenOfPrefix ;
+    if(dotPos != string::npos) {
+        lenOfSuffix = length - dotPos - 1;
+        lenOfPrefix = dotPos ;
+    }
+    else 
+        lenOfPrefix = length ;
+    size_t p  ;
+    char c ;
+    bool flag = false ;
+    for( p = 0 ; p < lenOfPrefix ; p ++) {
+        c = aEntryName[p];
+        if(c == 0x22 || c == 0x2A || c == 0x2B || c == 0x2C || c == 0x2E || c == 0x2F || \
+           c == 0x3A || c == 0x3B || c == 0x3C || c == 0x3D || c == 0x3E || c == 0x3 || \
+           c == 0x5B || c == 0x5C || c == 0x5D || c == 0x7C )  { // illegal characters ;
+            flag = true ;
+            break ;
+        }  
+    }
+    lenOfPrefix = p ;
+    if(lenOfPrefix > 8){
+        flag = true ;
+    }    
+    if(flag){
+        size_t len =  (6 <= p) ? 6 : p;
+        memcpy(iShortName,aEntryName,len);
+        iShortName[len] = '~';
+        iShortName[len + 1] = '1' ;
+		if(lenOfSuffix > 0){
+			memcpy(&iShortName[8],&aEntryName[dotPos + 1], ((3 <= lenOfSuffix) ? 3 : lenOfSuffix));
+		}
+		for(p = 0 ; p < 11 ; p++){
+			if(iShortName[p] >= 'a' && iShortName[p] <= 'z')
+				iShortName[p] = iShortName[p] + 'A' - 'a' ;
+		}
+		if(iParent)
+			iParent->MakeUniqueShortName(iShortName,len);
+    }
+    else {
+        memcpy(iShortName,aEntryName,lenOfPrefix);
+		if(lenOfSuffix > 0){
+			memcpy(&iShortName[8],&aEntryName[dotPos + 1], ((3 <= lenOfSuffix) ? 3 : lenOfSuffix));
+		}
+		for(p = 0 ; p < 11 ; p++){
+			if(iShortName[p] >= 'a' && iShortName[p] <= 'z')
+				iShortName[p] = iShortName[p] + 'A' - 'a' ;
+		}
+    }
+    
+	
+}
+void CDirectory::MakeUniqueShortName(unsigned char* rShortName,size_t aWavPos) const { 
+	list<CDirectory*>::const_iterator i = iDirectoryList.begin();
+	unsigned char nIndex = 1 ;
+	while(i != iDirectoryList.end()){
+		CDirectory* dir = (CDirectory*)(*i); 
+		if(0 == memcmp(rShortName,dir->iShortName,aWavPos + 1) &&
+			0 == memcmp(&rShortName[8],&(dir->iShortName[8]),3)) {
+			nIndex ++ ;
+		}
+		i++ ;
+	} 
+	if(nIndex < 10)
+		rShortName[aWavPos + 1] =  ('0' + nIndex) ;
+	else if( nIndex < 36) 
+		rShortName[aWavPos + 1] =  ('A' + nIndex - 10) ;
+	else {
+		nIndex = 10 ;
+		rShortName[aWavPos-1] = '~';
+		i = iDirectoryList.begin();
+		while(i != iDirectoryList.end()){
+			CDirectory* dir = (CDirectory*)(*i);
+			if(0 == memcmp(rShortName,dir->iShortName,aWavPos) &&
+				0 == memcmp(&rShortName[8],&(dir->iShortName[8]),3))
+				nIndex ++ ;
+			i++ ;
+		}
+		sprintf((char*)(&rShortName[aWavPos]),"%u",(unsigned int)(nIndex));
+		rShortName[aWavPos + 2] = 0x20;
+	}
+}
+/**
+Destructor: 
+1. To delete all the entries available in the form of directory structure
+2. Also to delete the current entry
+
+@internalComponent
+@released 
+*/
+
+FILESYSTEM_API CDirectory::~CDirectory()
+{
+	while(iDirectoryList.size() > 0)
+	{
+		delete iDirectoryList.front();
+		iDirectoryList.pop_front();
+	}
+}
+
+/**
+Function to initialize the time attributes of an entry
+
+@internalComponent
+@released 
+*/
+
+void CDirectory::InitializeTime()
+{
+	time_t rawtime;
+	time ( &rawtime );
+	iDateAndTime = localtime ( &rawtime );
+	iDate.iCurrentDate.Day = iDateAndTime->tm_mday;
+	iDate.iCurrentDate.Month = iDateAndTime->tm_mon+1; //As per FAT spec
+	iDate.iCurrentDate.Year = iDateAndTime->tm_year - 80;//As per FAT spec
+	iTime.iCurrentTime.Hour = iDateAndTime->tm_hour;
+	iTime.iCurrentTime.Minute = iDateAndTime->tm_min;
+	iTime.iCurrentTime.Seconds = iDateAndTime->tm_sec / 2;//As per FAT spec
+
+	iCreationDate = iDate.iImageDate;
+	iCreatedTime = iTime.iImageTime;
+	iLastAccessDate = iDate.iImageDate;
+	iLastWriteDate = iDate.iImageDate;
+	iLastWriteTime = iTime.iImageTime;
+}
+
+/**
+Function to initialize the entry name
+
+@internalComponent
+@released
+
+@param aEntryName - entry name need to be initialized
+*/
+FILESYSTEM_API void CDirectory::SetEntryName(string aEntryName)
+{
+	iEntryName = aEntryName;
+}
+
+/**
+Function to return the entry name
+
+@internalComponent
+@released
+
+@return iEntryName - the entry name
+*/
+
+FILESYSTEM_API string CDirectory::GetEntryName() const
+{
+	return iEntryName;
+}
+
+/**
+Function to initialize the file path
+
+@internalComponent
+@released
+
+@param aFilePath - where the current entry contents actually stored
+*/
+FILESYSTEM_API void CDirectory::SetFilePath(char* aFilePath)
+{
+	iFilePath.assign(aFilePath);
+}
+
+/**
+Function to return the file path
+
+@internalComponent
+@released
+
+@return iFilePath - the file path
+*/
+FILESYSTEM_API string CDirectory::GetFilePath() const
+{
+	return iFilePath;
+}
+
+/**
+Function to set the entry attribute
+
+@internalComponent
+@released
+
+@param aAttribute - entry attribute
+*/
+FILESYSTEM_API void CDirectory::SetEntryAttribute(char aAttribute)
+{
+	iAttribute = aAttribute;
+}
+
+/**
+Function to return the entry attribute
+
+@internalComponent
+@released
+
+@return iAttribute - the entry attribute
+*/
+FILESYSTEM_API char CDirectory::GetEntryAttribute() const
+{
+	return iAttribute;
+}
+
+
+/**
+Function to initialize the file size, this function is called only if the entry is of
+type File.
+
+@internalComponent
+@released
+
+@param aFileSize - the current entry file size
+*/
+FILESYSTEM_API void CDirectory::SetFileSize(unsigned int aFileSize)
+{
+	iFileSize = aFileSize;
+}
+
+/**
+Function to return the entry file size, this function is called only if the entry is of
+type File.
+
+@internalComponent
+@released
+
+@return iFileSize - the file size
+*/
+FILESYSTEM_API unsigned int CDirectory::GetFileSize() const
+{
+	return iFileSize;
+}
+
+/**
+Function to check whether this is a file 
+
+@internalComponent
+@released 
+
+@return iFileFlag - the File Flag
+*/
+bool CDirectory::IsFile() const 
+{
+	return (iAttribute & EAttrDirectory) == 0  ;
+}
+
+/**
+Function to return the entries Nt Reserved byte
+
+@internalComponent
+@released 
+
+@return iNtReserverd - the Nt Reserved byte
+*/
+char CDirectory::GetNtReservedByte() const
+{
+	return iNtReserved;
+}
+
+/**
+Function to return the entry Creation time in milli-seconds.
+
+@internalComponent
+@released
+
+@return iCreatedTimeMsecs - created time in Milli-seconds
+*/
+char CDirectory::GetCreationTimeMsecs() const
+{
+	return iCreationTimeMsecs;
+}
+
+/**
+Function to return the entry Created time
+
+@internalComponent
+@released
+
+@retun iCreatedTime - created time
+*/
+unsigned short int CDirectory::GetCreatedTime() const
+{
+	return iCreatedTime;
+}
+
+/**
+Function to return the entry Created date
+
+@internalComponent
+@released
+
+@return iCreationDate - created date
+*/
+unsigned short int CDirectory::GetCreationDate() const
+{
+	return iCreationDate;
+}
+
+/**
+Function to return the entry last accessed date
+
+@internalComponent
+@released
+
+@return iLastAccessDate - last access date
+*/
+unsigned short int CDirectory::GetLastAccessDate() const
+{
+	return iLastAccessDate;
+}
+
+/**
+Function to set high word cluster number
+
+@internalComponent
+@released
+
+@param aHiClusterNumber - high word of current cluster number
+*/
+void CDirectory::SetClusterNumberHi(unsigned short int aHiClusterNumber)
+{
+	iClusterNumberHi = aHiClusterNumber;
+}
+
+/**
+Function to return high word cluster number
+
+@internalComponent
+@released
+
+@return iClusterNumberHi - high word of cluster number
+*/
+unsigned short int CDirectory::GetClusterNumberHi() const
+{
+	return iClusterNumberHi;
+}
+
+/**
+Function to set low word cluster number
+
+@internalComponent
+@released 
+
+@param aLowClusterNumber - low word of current cluster number
+*/
+void CDirectory::SetClusterNumberLow(unsigned short int aLowClusterNumber)
+{
+	iClusterNumberLow = aLowClusterNumber;
+}
+
+/**
+Function to return low word cluster number
+
+@internalComponent
+@released 
+
+@return iClusterNumberLow - low word of cluster number
+*/
+unsigned short int CDirectory::GetClusterNumberLow() const
+{
+	return iClusterNumberLow;
+}
+
+/**
+Function to return last write date
+
+@internalComponent
+@released 
+
+@return iLastWriteDate - last write date
+*/
+unsigned short int CDirectory::GetLastWriteDate() const
+{
+	return iLastWriteDate;
+}
+
+/**
+Function to return last write time
+
+@internalComponent
+@released
+
+@return iLastWriteTime - last write time
+*/
+unsigned short int CDirectory::GetLastWriteTime() const
+{
+	return iLastWriteTime;
+}
+
+/**
+Function to return sub directory/file list
+
+@internalComponent
+@released
+
+@return iDirectoryList -  entry list
+*/
+FILESYSTEM_API EntryList* CDirectory::GetEntryList()
+{
+	return &iDirectoryList;
+}
+
+/**
+Function to insert a entry into Directory list. Also this function can be used 
+extensively to construct tree form of directory structure.
+
+@internalComponent
+@released
+
+@param aEntry - the entry to be inserted
+*/
+FILESYSTEM_API void CDirectory::InsertIntoEntryList(CDirectory* aEntry)
+{
+    aEntry->iParent = this ;
+	iDirectoryList.push_back(aEntry);
+}
+ 
+FILESYSTEM_API bool CDirectory::GetShortEntry(TShortDirEntry& rEntry) {
+  
+    memcpy(rEntry.DIR_Name,iShortName,sizeof(rEntry.DIR_Name)); 
+    rEntry.DIR_Attr = iAttribute;
+    rEntry.DIR_NTRes = 0 ;
+    rEntry.DIR_CrtTimeTenth = 0 ;        
+    memcpy(rEntry.DIR_CrtTime,&iCreatedTime,sizeof(rEntry.DIR_CrtTime)); 
+    memcpy(rEntry.DIR_CrtDate,&iCreationDate,sizeof(rEntry.DIR_CrtDate));
+    memcpy(rEntry.DIR_LstAccDate,&iLastAccessDate,sizeof(rEntry.DIR_LstAccDate));
+    memcpy(rEntry.DIR_FstClusHI,&iClusterNumberHi,sizeof(rEntry.DIR_FstClusHI)); 
+    memcpy(rEntry.DIR_WrtTime,&iLastWriteTime,sizeof(rEntry.DIR_WrtTime)); 
+    memcpy(rEntry.DIR_WrtDate,&iLastWriteDate,sizeof(rEntry.DIR_WrtDate)); 
+    memcpy(rEntry.DIR_FstClusLO,&iClusterNumberLow,sizeof(rEntry.DIR_FstClusLO)); 
+    memcpy(rEntry.DIR_FileSize,&iFileSize,sizeof(rEntry.DIR_FileSize)); 
+    return true ;
+}
+static unsigned char ChkSum(const unsigned char* pFcbName) {
+    short fcbNameLen ;
+    unsigned char sum = 0 ;
+    for(fcbNameLen = 11 ; fcbNameLen != 0 ; fcbNameLen --) {
+        sum = ((sum & 1) ? 0x80 : 0 ) + (sum >> 1 ) + *pFcbName++ ; 
+    }
+    return sum ;        
+}
+ 
+FILESYSTEM_API bool CDirectory::GetLongEntries(list<TLongDirEntry>& rEntries) {
+    if(0 == iEntryName.compare(".") || 0 == iEntryName.compare("..")){
+        return false ;
+    }
+    rEntries.clear();
+    TLongDirEntry entry ; 
+	UTF16String uniStr(iEntryName.c_str() , iEntryName.length());
+    size_t length = uniStr.length() ;
+    const size_t KBytesPerEntry = (sizeof(entry.LDIR_Name1) + sizeof(entry.LDIR_Name2) +  \
+		sizeof(entry.LDIR_Name3)) / 2 ;  
+    size_t packs =  (length + KBytesPerEntry) / KBytesPerEntry  ;
+    size_t buflen = packs * KBytesPerEntry;
+    TUint16* buffer = new TUint16[buflen];
+    if(!buffer)
+        return false ;
+    memset(buffer,0xff,(buflen << 1));    
+    memcpy(buffer,uniStr.c_str(),(length << 1)); 
+	buffer[length] = 0;
+    entry.LDIR_Attr = (unsigned char)EAttrLongName;
+    entry.LDIR_Chksum = ChkSum(iShortName);
+    entry.LDIR_FstClusLO[0] = 0;
+	entry.LDIR_FstClusLO[1] = 0;
+    entry.LDIR_Type = 0;
+    TUint16* ptr = buffer ;
+    for(size_t n = 1 ; n <= packs ; n++ ) {
+        entry.LDIR_Ord = n ;
+        if(n == packs ){
+            entry.LDIR_Ord |= 0x40 ;
+        }
+        memcpy(entry.LDIR_Name1,ptr,sizeof(entry.LDIR_Name1));
+        ptr += (sizeof(entry.LDIR_Name1) / 2) ;
+        memcpy(entry.LDIR_Name2,ptr,sizeof(entry.LDIR_Name2));
+        ptr += (sizeof(entry.LDIR_Name2) / 2);
+        memcpy(entry.LDIR_Name3,ptr,sizeof(entry.LDIR_Name3));
+        ptr += (sizeof(entry.LDIR_Name3) / 2);
+        rEntries.push_front(entry);
+    }
+    
+    delete []buffer ;
+    return true ; 
+}
--- a/imgtools/imglib/filesystem/source/dirregion.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/source/dirregion.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,690 +1,505 @@
-/*
-* 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: 
-* Class receives tree structured directory and file information. And 
-* prepares the cluster versus content MAP by traversing through the same. 
-* Later all the prepared clusters are written into image file.
-* @internalComponent
-* @released
-*
-*/
-
-
-#include "dirregion.h"
-
-/**
-Constructor:
-1.Get the instance of class CCluster
-2.Intializes the Cluster pointer
-3.Intialize the flags and other variables
-
-@internalComponent
-@released
-
-@param aNodeList - Root node placed in this list
-@param aFileSystemPtr - CFileSystem class pointer
-*/
-CDirRegion::CDirRegion(EntryList aNodeList,
-					   CFileSystem * aFileSystemPtr):
-					   iCurrentDirEntry(false),
-					   iParentDirEntry(false),
-					   iFirstCluster(true),
-   					   iNodeList(aNodeList)
-{
-	iClusterSize = aFileSystemPtr->GetClusterSize();
-	iRootDirSizeInBytes = (aFileSystemPtr->GetRootDirSectors () * 
-						   aFileSystemPtr->GetBytesPerSector());
-	int totalClusters = aFileSystemPtr->GetTotalCluster();
-	iClusterPtr = CCluster::Instance(iClusterSize,totalClusters);
-	if(iClusterPtr == NULL)
-	{
-		throw ErrorHandler(CLUSTERERROR,"Instance creation error", __FILE__, __LINE__);
-	}
-	iClusterSize = iClusterPtr->GetClusterSize();
-}
-
-/**
-Destructor: 
-1. Clean the Node List 
-2. Clean the instance of Cluster object 
-3. Clean the Cluster MAP.
-4. Invokes the DestroyShortEntryList to clear the contents of static GShortEntryList.
-
-@internalComponent
-@released
-*/
-CDirRegion::~CDirRegion()
-{
-	if(iNodeList.size() > 0)
-	{
-		//Delete the root node
-		delete iNodeList.front();
-	}
-	if(iClusterPtr != NULL)
-	{
-		delete iClusterPtr;
-		iClusterPtr = NULL;
-	}
-	iClusterMap.clear();
-	ClongName::DestroyShortEntryList();
-}
-
-/**
-Function to return Clusters per entry map(input for FAT table generator function) 
-container
-
-@internalComponent
-@released
-
-@return - returns clusters per entry map container
-*/
-TClustersPerEntryMap* CDirRegion::GetClustersPerEntryMap() const
-{
-	return iClusterPtr->GetClustersPerEntryMap();
-}
-
-/**
-Function responsible to write all the clusters available in iClusterMap
-into file. 
-
-@internalComponent
-@released
-
-@param aOutPutStream - output file stream to write clusters in it
-*/
-void CDirRegion::WriteClustersIntoFile(OfStream& aOutPutStream)
-{
-	StringMap::iterator mapBeginIter = iClusterMap.begin();
-	StringMap::iterator mapEndIter= iClusterMap.end();
-	//MAPs are sorted associative containers, so no need to sort
-	String tempString;
-	while(mapBeginIter != mapEndIter)
-	{
-		tempString = (*mapBeginIter++).second;
-		aOutPutStream.write(tempString.c_str(),tempString.length());
-	}
-	aOutPutStream.flush();
-	if(aOutPutStream.bad())
-	{
-		throw ErrorHandler(FILEWRITEERROR, __FILE__, __LINE__);
-	}
-}
-
-
-/**
-Function takes the full entry name and formats it as per FAT spec requirement
-Requirement:
-1. All the names should be of 11 characters length.
-2. Name occupies 8 characters and the extension occupies 3 characters.
-3. If the name length is less than 8 characters, padd remaining characters with '0x20' 
-4. If the extension length is less than 3 characters, padd remaining characters with '0x20' 
-5. If the Name or extension exceeds from its actual length then it is treated as long name.
-
-@internalComponent
-@released
-
-@param aString - the String needs to be formatted
-@param aAttrValue - the entry attribute
-*/
-void CDirRegion::FormatName(String& aString, char aAttrValue)
-{
-	if(!aString.empty())
-	{
-		if((*aString.begin()) != KDot)
-		{
-			//Get the file extension start index
-			int extensionStartIndex = aString.find_last_of (KDot);
-			if(aAttrValue != EAttrDirectory && extensionStartIndex != -1)
-			{
-				//Erase the dot, because it is not required to be written in the FAT image
-				aString.erase(extensionStartIndex,1);
-				//Apply Space padding for the Name
-				aString.insert (extensionStartIndex,(ENameLength - extensionStartIndex), KSpace);
-				int totalStringLength = aString.length();
-				//Apply Space padding for the  Extension
-				if(totalStringLength < ENameLengthWithExtension)
-				{
-					aString.insert(totalStringLength,(ENameLengthWithExtension - totalStringLength), KSpace);
-					return;
-				}
-			}
-			else
-			{
-				int nameEndIndex = aString.length();
-				//Apply Space padding for the directory Name
-				aString.insert(nameEndIndex,(ENameLengthWithExtension - nameEndIndex),KSpace);
-				return;
-			}
-		}
-		else
-		{	//Apply Space padding for either '.' or ".."
-			aString.append((ENameLengthWithExtension - aString.length()),KSpace);
-			return;
-		}
-	}
-	else
-	{
-		throw ErrorHandler(EMPTYFILENAME, __FILE__, __LINE__);
-	}
-}
-
-/**
-Function responsible to classify the entry name as long name or regular name.
-
-@internalComponent
-@released
-
-@param aEntry - the directory entry
-@return - returns true if it is long name else false.
-*/
-bool CDirRegion::IsLongEntry(CDirectory* aEntry) const
-{
-	String entryName = aEntry->GetEntryName();
-	unsigned int receivedNameLength = entryName.length();
-	unsigned int firstDotLocation = entryName.find_first_of(KDot);
-	unsigned int lastDotLocation = entryName.find_last_of(KDot);
-
-	if(firstDotLocation == lastDotLocation)
-	{
-		if(aEntry->GetEntryAttribute() == EAttrDirectory)
-		{
-			// If the directory name length is more than 8 characters, then it is a long name
-			if(receivedNameLength > ENameLength)
-			{
-				return true;
-			}
-		}
-		else
-		{
-			int extensionIndex = lastDotLocation;
-			unsigned int fileExtensionLength = receivedNameLength - extensionIndex - 1;
-			/*Either the full name length is greater than 11 or the extension 
-			 *length is greater than 3, then it is considered as long name.
-			 */
-			if((receivedNameLength > ENameLengthWithExtension) 
-			   || (fileExtensionLength > EExtensionLength))
-			{
-				return true;
-			}
-		}
-		return false;
-	}
-	else
-	{
-		//If the name contains multiple dots, then it is a long name.
-		return true;	
-	}
-}
-
-/**
-Function responsible to 
-1. Invoke long name class
-2. Invoke the methods to create long and short entries
-3. Receive the string filled with long entries
-
-@internalComponent
-@released
-
-@param aEntry - the entry
-@param aDirString - long name entry appended to this string
-*/
-
-void CDirRegion::CreateLongEntries(CDirectory* aEntry,String& aDirString)
-{
-	ClongName aLongNameObject(iClusterPtr,aEntry);
-	String tempString = aLongNameObject.CreateLongEntries();
-	if(tempString.length() == 0)
-	{
-		tempString.erase();
-		throw ErrorHandler(EMPTYFILENAME, __FILE__, __LINE__);
-	}
-	else
-	{
-		aDirString.append(tempString.c_str(),tempString.length());
-		tempString.erase();
-		WriteEntryToString(aLongNameObject.CreateShortEntry(aEntry),aDirString);
-	}
-}
-
-/**
-Function takes a single entry and writes its attributes into tempString.
-Later this string is appended with the string received in the argument
-
-@internalComponent
-@released
-
-@param aEntry - the entry which attributes are needs to be written into aString
-@param aString - entry attributes appended into this string
-*/
-void CDirRegion::WriteEntryToString(CDirectory* aEntry,String& aString)
-{
-	String tempString;
-	String entryName = aEntry->GetEntryName();
-	tempString.append(ToUpper(entryName));
-	//appends the attributes only once
-	tempString.append(KWriteOnce, aEntry->GetEntryAttribute());
-	tempString.append(KWriteOnce, aEntry->GetNtReservedByte());
-	tempString.append(KWriteOnce, aEntry->GetCreationTimeMsecs());
-	unsigned short int createdTime = aEntry->GetCreatedTime();
-	tempString.append(ToString(createdTime));
-	unsigned short int creationDate = aEntry->GetCreationDate();
-	tempString.append(ToString(creationDate));
-	unsigned short int lastAccessDate = aEntry->GetLastAccessDate();
-	tempString.append(ToString(lastAccessDate));
-	unsigned short int clusterNumberHi = aEntry->GetClusterNumberHi();
-	tempString.append(ToString(clusterNumberHi));
-	unsigned short int lastWriteTime = aEntry->GetLastWriteTime();
-	tempString.append(ToString(lastWriteTime));
-	unsigned short int lastWriteDate = aEntry->GetLastWriteDate();
-	tempString.append(ToString(lastWriteDate));
-	unsigned short int clusterNumberLow = aEntry->GetClusterNumberLow();
-	tempString.append(ToString(clusterNumberLow));
-	unsigned int fileSize = aEntry->GetFileSize();
-	tempString.append(ToString(fileSize));
-
-	aString.append(tempString.c_str(),KDirectoryEntrySize);
-	tempString.erase();
-}
-
- 
-
-/**
-Function responsible to 
-1. Read the file content and write into string.
-2. Invoke the function to push data clusters into cluster Map
-
-@internalComponent
-@released
-
-@param aEntry - the directory entry node
-*/
-void CDirRegion::WriteFileDataInToCluster(CDirectory* aEntry)
-{
-	iInputStream.open(aEntry->GetFilePath().c_str(),Ios::binary);
-	if(iInputStream.fail() == true )
-	{
-		throw ErrorHandler(FILEOPENERROR,(char*)aEntry->GetFilePath().c_str(),__FILE__,__LINE__);
-	}
-	else
-	{
-		iInputStream.seekg (0,Ios::end);
-		Long64 fileSize = iInputStream.tellg(); 
-		iInputStream.seekg(0,Ios::beg);
-		char* dataBuffer = (char*)malloc((unsigned int)fileSize);
-		if(dataBuffer == 0)
-		{
-			throw ErrorHandler(MEMORYALLOCATIONERROR, __FILE__, __LINE__);
-		}
-		//Read the whole file in one short
-		iInputStream.read (dataBuffer,fileSize);
-		
-		Long64 bytesRead = (unsigned int)iInputStream.tellg();
-		if((iInputStream.bad()) || (bytesRead != fileSize))
-		{
-			throw ErrorHandler(FILEREADERROR,(char*)aEntry->GetFilePath().c_str(), __FILE__, __LINE__);
-		}
-		String clusterData(dataBuffer,(unsigned int)bytesRead);
-		PushStringIntoClusterMap(iClusterPtr->GetCurrentClusterNumber(),clusterData,iClusterSize,aEntry->GetEntryAttribute());
-	}
-	iInputStream.close();
-}
-
-
-/**
-Function invokes 
-1. CheckEntry function, to identify whether the received entry list is proper or not.
-2. Invokes CreateDirEntry, to create directory and data portion of FAT image.
-
-@internalComponent
-@released
-  
-*/
-void CDirRegion::Execute()
-{
-	CheckEntry(iNodeList);
-	CreateDirEntry(iNodeList.front(),KParentDirClusterNumber);
-}
-
-/**
-Function is to initialize the Parent directory entry with parent cluster number
-and appends all the attributes into the string (aString).
-
-@internalComponent
-@released
-
-@param aParDirClusterNumber - parent directory cluster number
-@param aString - parent directory entry attributes appended to this string
-*/
-void CDirRegion::CreateAndWriteParentDirEntry(unsigned int aParDirClusterNumber,String& aString)
-{
-	const char* parentDirName = ".."; //Indicates parent directory entry name
-	CDirectory* parentDirectory = new CDirectory((char*)parentDirName);
-
-	parentDirectory->SetEntryAttribute(EAttrDirectory);
-	parentDirectory->SetClusterNumberLow((unsigned short) (aParDirClusterNumber & KHighWordMask));
-	parentDirectory->SetClusterNumberHi((unsigned short) (aParDirClusterNumber >> KBitShift16));
-
-	String tempString(parentDirectory->GetEntryName());
-	FormatName(tempString,EAttrDirectory);
-	parentDirectory->SetEntryName(tempString);
-	tempString.erase();
-	
-	WriteEntryToString(parentDirectory,aString);
-	iParentDirEntry = true;
-	delete parentDirectory;
-	parentDirectory = NULL;
-}
-
-/**
-Function responsible to 
-1. Initialize the Current directory entry attribute
-2. Write the entry attributes into received string
-
-@internalComponent
-@released
-
-@param aCurDirClusterNumber - Current directory Cluster number
-@param aString - the entry attributes should be appended to this string
-*/
-void CDirRegion::CreateAndWriteCurrentDirEntry(unsigned int aCurClusterNumber,String& aString)
-{
-	const char* currentDirName = "."; //Indicates Current Directory entry name
-	iCurEntryClusterNumber = aCurClusterNumber;
-	CDirectory* currentDirectory = new CDirectory((char*)currentDirName);
-
-	currentDirectory->SetEntryAttribute(EAttrDirectory);
-	currentDirectory->SetClusterNumberLow((unsigned short) (iCurEntryClusterNumber & KHighWordMask));
-	currentDirectory->SetClusterNumberHi((unsigned short) (iCurEntryClusterNumber >> KBitShift16));
-
-	String tempString(currentDirectory->GetEntryName());
-	FormatName(tempString,EAttrDirectory);
-	currentDirectory->SetEntryName(tempString);
-	tempString.erase();
-
-	WriteEntryToString(currentDirectory,aString);
-	iCurrentDirEntry = true;
-	delete currentDirectory;
-	currentDirectory = NULL;
-}
-
-/**
-Function responsible to push the directory entry clusters into cluster MAP only if the
-directory entry string size is greater than the cluster size.
-
-@internalComponent
-@released
-
-@param aNumber - is the Cluster Key used to insert the cluster into cluster map
-@param aString - is the directory entry string
-@param aClustersRequired - No of clusters required to hold this string
-*/
-
-void CDirRegion::PushDirectoryEntryString(unsigned int aNumber,String& aString,int aClustersRequired)
-{
-	int clusterCount = 0;
-	int clusterKey = aNumber;
-	iClusterPtr->CreateMap(aNumber,clusterKey);
-	iClusterMap[clusterKey] =	aString.substr(clusterCount*iClusterSize,iClusterSize);
-	++clusterCount;
-	String clusterSizeString;
-	for(; clusterCount < aClustersRequired; ++clusterCount)
-	{
-		clusterKey = iClusterPtr->GetCurrentClusterNumber();
-		clusterSizeString = aString.substr(clusterCount*iClusterSize,iClusterSize);
-		clusterSizeString.append((iClusterSize - clusterSizeString.length()),0);
-		iClusterMap[clusterKey] = clusterSizeString;
-		iClusterPtr->CreateMap(aNumber,clusterKey);
-		iClusterPtr->UpdateNextAvailableClusterNumber();
-	}
-}
-
-/**Function responsible to 
-1. Convert the string into equal size clusters of cluster size
-2. Insert the clusters into Cluster MAP
-
-@internalComponent
-@released
-
-@param aNumber - cluster number, used to map the cluster
-@param aString - reference of input string
-@param aClusterSize - used to split the string
-@param aAttribute - current entry attribute
-*/
-void CDirRegion::PushStringIntoClusterMap(unsigned int aNumber, String& aString, unsigned long int aClusterSize,char aAttribute)
-{
-	int receivedStringLength = aString.length();
-	/* Precaution, once the map is initialized with specific cluster number don't over write
-	 * it once again. Look for the cluster number within the existing MAP and then proceed with 
-	 * filling in the cluster.
-	 */
-	StringMap::iterator iter= iClusterMap.find(aNumber);
-	if(iter == iClusterMap.end())
-	{
-		/* The length of the cluster content (aString) can be more or less than the cluster size, 
-		 * hence, calculate the total number of clusters required.
-		 */
-		int clustersRequired = receivedStringLength / aClusterSize;
-		if((receivedStringLength % aClusterSize) > 0)
-		{
-			++clustersRequired;
-		}
-		if((clustersRequired > 1) && (aAttribute == EAttrDirectory))
-		{
-			PushDirectoryEntryString(aNumber,aString,clustersRequired);
-			return;
-		}
-		int updatedClusterNumber = aNumber;
-		String clusterSizeString;
-		for(short int clusterCount = 0; clusterCount < clustersRequired; ++clusterCount)
-		{
-			/* In case of the contents occupying more than one cluster, break the contents into
-			 * multiple parts, each one measuring as that of the cluster size.
-			 */
-			clusterSizeString = aString.substr(clusterCount * aClusterSize,aClusterSize);
-			iClusterPtr->CreateMap(aNumber,updatedClusterNumber);
-			if(clusterSizeString.length() < aClusterSize)
-			{
-				/* Copied string size is less than cluster size, fill the remaining space
-				 * with zero
-				 */
-				clusterSizeString.append((aClusterSize - clusterSizeString.length()),0);
-			}
-			// Insert the String into ClusterMap	
-			iClusterMap[updatedClusterNumber] = clusterSizeString;
-		
-			iClusterPtr->UpdateNextAvailableClusterNumber();
-			updatedClusterNumber = iClusterPtr->GetCurrentClusterNumber ();
-		}
-		/* In the above loop, cluster number is incremented to point to the next entry.
-		 * However, before writing a directory or a volume id entry, it is always ensured 
-		 * to get the next cluster number. Hence in this case, it is required to decrement
-		 * the cluster number, so that the pointer points to the end of the cluster occupied.
-		 */
-		if(aAttribute == EAttrDirectory || aAttribute == EAttrVolumeId)
-		{
-			iClusterPtr->DecrementCurrentClusterNumber ();
-		}
-	}
-}
-
-/**
-Function is responsible to take in the tree structured directory 
-information and to initialize the starting cluster in the Cluster Map.
-
-@internalComponent
-@released
-
-@param aNodeList - the list which holds root entry
-*/
-void CDirRegion::CheckEntry(EntryList aNodeList)
-{
-	if(aNodeList.size() > 0)
-	{
-		if(iRootDirSizeInBytes > 0)
-		{
-			//FAT16 Root entries are written into Cluster 1
-			iClusterKey = KFat16RootEntryNumber;
-		}
-		else
-		{
-			//FAT32 Root entries are written into Cluster 2			
-			iClusterPtr->UpdateNextAvailableClusterNumber();
-			iClusterKey = KFat32RootEntryNumber; 
-		}
-		if(aNodeList.front()->GetEntryList()->size() <= 0)
-		{
-			throw ErrorHandler(NOENTRIESFOUND, __FILE__, __LINE__);
-		}
-	}
-	else
-	{
-		throw ErrorHandler(ROOTNOTFOUND, __FILE__, __LINE__);
-	}
-}
-
-/**
-Function receives Tree structured folder information and does the following:
-1. Generates Directory Entry portion of FAT image recursively.
-2. If it finds the entry as file then writes its contents.
-3. If the entry is long name then longfilename class invoked to create long entries.
-
-@internalComponent
-@released
-
-@param aEntry  - Subdirectory pointer of root directory
-@param aParentDirClusterNumber - parent directory cluster number
-*/
-void CDirRegion::CreateDirEntry(CDirectory* aEntry,unsigned int aParentDirClusterNumber)
-{
-	unsigned int currentDirClusterNumber = 0;
-	int rootClusterSize = 0;
-	if(iFirstCluster == true)
-	{
-			iCurrentDirEntry = true;
-			iParentDirEntry = true;
-			/**Root directory and Normal directory has one difference.
-			FAT16 : Root cluster occupies 32 sectors
-			FAT32 : Root cluster occupies only one cluster
-			*/
-			rootClusterSize = (iRootDirSizeInBytes > 0)?iRootDirSizeInBytes:iClusterSize; 
-	}
-	else
-	{
-		currentDirClusterNumber = Get32BitClusterNumber(aEntry->GetClusterNumberHi(),
-														aEntry->GetClusterNumberLow());
-	}
-	
-	//printIterator used while printing the entries
-	EntryList::iterator printIterator = aEntry->GetEntryList()->begin(); 
-	//traverseIterator used during recursive call
-	EntryList::iterator traverseIterator = printIterator;
-	
-	unsigned int dirEntryCount = aEntry->GetEntryList()->size();
-
-	String dirString;
-	String nameString;
-	CDirectory* tempDirEntry = (*printIterator);
-	//Writes all the Directory entries available in one Directory entry
-	while(dirEntryCount > 0)
-	{
-		tempDirEntry = (*printIterator);
-		
-		tempDirEntry->SetClusterNumberHi(iClusterPtr->GetHighWordClusterNumber());
-		tempDirEntry->SetClusterNumberLow(iClusterPtr->GetLowWordClusterNumber());
-
-		/* Every directory should have current and parent directory entries in its
-		 * respective cluster. Hence Create the current and parent directory entries 
-		 * only if it is not created already.
-		 */
-		if(!iCurrentDirEntry && !iParentDirEntry)
-		{
-			CreateAndWriteCurrentDirEntry(currentDirClusterNumber,dirString);
-			iClusterKey = currentDirClusterNumber;
-			CreateAndWriteParentDirEntry(aParentDirClusterNumber,dirString);
-		}
-		MessageHandler::ReportMessage(INFORMATION,
-									  ENTRYCREATEMSG,
-									  (char*)tempDirEntry->GetEntryName().c_str());
-		if(!IsLongEntry(tempDirEntry))
-		{
-			nameString.assign(tempDirEntry->GetEntryName());
-			FormatName(nameString,tempDirEntry->GetEntryAttribute());
-			tempDirEntry->SetEntryName(nameString);
-			nameString.erase();
-			WriteEntryToString(tempDirEntry,dirString);
-		}
-		else
-		{
-			CreateLongEntries(tempDirEntry,dirString);
-		}
-		if(tempDirEntry->IsFile())
-		{
-			WriteFileDataInToCluster(tempDirEntry);
-		}
-		else
-		{
-			iClusterPtr->UpdateNextAvailableClusterNumber ();
-		}
-		++printIterator;
-		--dirEntryCount;
-	}
-
-	iCurrentDirEntry = false;
-	iParentDirEntry = false;
-	aParentDirClusterNumber = currentDirClusterNumber;
-	if(iFirstCluster == true)
-	{
-		PushStringIntoClusterMap(iClusterKey,dirString,rootClusterSize,aEntry->GetEntryAttribute());
-		iFirstCluster = false;
-	}
-	else
-	{
-		PushStringIntoClusterMap(iClusterKey,dirString,iClusterSize,aEntry->GetEntryAttribute());
-	}
-
-	dirEntryCount = aEntry->GetEntryList()->size();
-
-	//Recursive algorithm to print all entries
-	while(dirEntryCount > 0)
-	{
-		if(aEntry->GetEntryList()->size() > 0)
-		{		
-			CreateDirEntry((*traverseIterator),aParentDirClusterNumber);
-		}
-		--dirEntryCount;
-		//if no entries found don't go deep
-		if(dirEntryCount > 0)
-		{
-			aEntry = (*++traverseIterator);
-		}
-	}
-}
-
-/**
-Function responsible to convert two 16 bit words into single 32 bit integer
-
-@internalComponent
-@released
-
-@param aHighWord - 16 bit high word
-@param aLowWord - 16 bit low word
-@return returns the 32 bit integer
-*/
-unsigned int CDirRegion::Get32BitClusterNumber(unsigned int aHighWord, unsigned int aLowWord)
-{
-	unsigned int clusterNumber = aHighWord;
-	clusterNumber <<= KBitShift16;
-	clusterNumber |= aLowWord;
-	return clusterNumber;
-}
+/*
+* 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: 
+* Class receives tree structured directory and file information. And 
+* prepares the cluster versus content MAP by traversing through the same. 
+* Later all the prepared clusters are written into image file.
+* @internalComponent
+* @released
+*
+*/
+
+
+#include "dirregion.h"
+#include "directory.h"
+/**
+Constructor:
+1.Get the instance of class CCluster
+2.Intializes the Cluster pointer
+3.Intialize the flags and other variables
+
+@internalComponent
+@released
+
+@param aNodeList - Root node placed in this list
+@param aFileSystemPtr - CFileSystem class pointer
+*/
+CDirRegion::CDirRegion(EntryList aNodeList,
+					   CFileSystem * aFileSystemPtr):
+					   iCurrentDirEntry(false),
+					   iParentDirEntry(false),
+					   iFirstCluster(true),
+   					   iNodeList(aNodeList)
+{
+	iClusterSize = aFileSystemPtr->GetClusterSize();
+	iRootDirSizeInBytes = (aFileSystemPtr->GetRootDirSectors () * 
+						   aFileSystemPtr->GetBytesPerSector());
+	int totalClusters = aFileSystemPtr->GetTotalCluster();
+	iClusterPtr = CCluster::Instance(iClusterSize,totalClusters);
+	if(iClusterPtr == NULL)
+	{
+		throw ErrorHandler(CLUSTERERROR,"Instance creation error", __FILE__, __LINE__);
+	}
+	iClusterSize = iClusterPtr->GetClusterSize();
+}
+
+/**
+Destructor: 
+1. Clean the Node List 
+2. Clean the instance of Cluster object 
+3. Clean the Cluster MAP.
+4. Invokes the DestroyShortEntryList to clear the contents of static GShortEntryList.
+
+@internalComponent
+@released
+*/
+CDirRegion::~CDirRegion()
+{
+	if(iNodeList.size() > 0)
+	{
+		//Delete the root node
+		delete iNodeList.front();
+	}
+	if(iClusterPtr != NULL)
+	{
+		delete iClusterPtr;
+		iClusterPtr = NULL;
+	}
+	iClusterMap.clear();
+	ClongName::DestroyShortEntryList();
+}
+
+/**
+Function to return Clusters per entry map(input for FAT table generator function) 
+container
+
+@internalComponent
+@released
+
+@return - returns clusters per entry map container
+*/
+TClustersPerEntryMap* CDirRegion::GetClustersPerEntryMap() const
+{
+	return iClusterPtr->GetClustersPerEntryMap();
+}
+
+/**
+Function responsible to write all the clusters available in iClusterMap
+into file. 
+
+@internalComponent
+@released
+
+@param aOutPutStream - output file stream to write clusters in it
+*/
+void CDirRegion::WriteClustersIntoFile(OfStream& aOutPutStream)
+{
+	StringMap::iterator mapBeginIter = iClusterMap.begin();
+	StringMap::iterator mapEndIter= iClusterMap.end();
+	//MAPs are sorted associative containers, so no need to sort
+	string tempString;
+	while(mapBeginIter != mapEndIter)
+	{
+		tempString = (*mapBeginIter++).second;
+		aOutPutStream.write(tempString.c_str(),tempString.length());
+	}
+	aOutPutStream.flush();
+	if(aOutPutStream.bad())
+	{
+		throw ErrorHandler(FILEWRITEERROR, __FILE__, __LINE__);
+	}
+}
+
+/**
+Function responsible to 
+1. Read the file content and write into string.
+2. Invoke the function to push data clusters into cluster Map
+
+@internalComponent
+@released
+
+@param aEntry - the directory entry node
+*/
+void CDirRegion::WriteFileDataInToCluster(CDirectory* aEntry)
+{
+	iInputStream.open(aEntry->GetFilePath().c_str(),ios_base::binary);
+	if(iInputStream.fail() == true )
+	{
+		throw ErrorHandler(FILEOPENERROR,(char*)aEntry->GetFilePath().c_str(),__FILE__,__LINE__);
+	}
+	else
+	{
+		iInputStream.seekg (0,ios_base::end);
+		Long64 fileSize = iInputStream.tellg(); 
+		iInputStream.seekg(0,ios_base::beg);
+		char* dataBuffer = (char*)malloc((unsigned int)fileSize);
+		if(dataBuffer == 0)
+		{
+			throw ErrorHandler(MEMORYALLOCATIONERROR, __FILE__, __LINE__);
+		}
+		//Read the whole file in one short
+		iInputStream.read (dataBuffer,fileSize);
+		
+		Long64 bytesRead = (unsigned int)iInputStream.tellg();
+		if((iInputStream.bad()) || (bytesRead != fileSize))
+		{
+			throw ErrorHandler(FILEREADERROR,(char*)aEntry->GetFilePath().c_str(), __FILE__, __LINE__);
+		}
+		string clusterData(dataBuffer,(unsigned int)bytesRead);
+		PushStringIntoClusterMap(iClusterPtr->GetCurrentClusterNumber(),clusterData,iClusterSize,aEntry->GetEntryAttribute());
+	}
+	iInputStream.close();
+}
+
+
+/**
+Function invokes 
+1. CheckEntry function, to identify whether the received entry list is proper or not.
+2. Invokes CreateDirEntry, to create directory and data portion of FAT image.
+
+@internalComponent
+@released
+  
+*/
+void CDirRegion::Execute()
+{
+	CheckEntry(iNodeList);
+	CreateDirEntry(iNodeList.front(),KParentDirClusterNumber);
+}
+
+/**
+Function is to initialize the Parent directory entry with parent cluster number
+and appends all the attributes into the string (aString).
+
+@internalComponent
+@released
+
+@param aParDirClusterNumber - parent directory cluster number
+@param aString - parent directory entry attributes appended to this string
+*/
+void CDirRegion::CreateAndWriteParentDirEntry(unsigned int aParDirClusterNumber,string& aString)
+{
+	CDirectory* parentDirectory = new CDirectory("..",NULL);
+
+	parentDirectory->SetEntryAttribute(EAttrDirectory);
+	parentDirectory->SetClusterNumberLow((unsigned short) (aParDirClusterNumber & KHighWordMask));
+	parentDirectory->SetClusterNumberHi((unsigned short) (aParDirClusterNumber >> KBitShift16));
+
+	TShortDirEntry entry ;
+	parentDirectory->GetShortEntry(entry);
+	aString.append((const char*)(&entry),sizeof(entry));
+	iParentDirEntry = true;
+	delete parentDirectory;
+	parentDirectory = NULL;
+}
+
+/**
+Function responsible to 
+1. Initialize the Current directory entry attribute
+2. Write the entry attributes into received string
+
+@internalComponent
+@released
+
+@param aCurDirClusterNumber - Current directory Cluster number
+@param aString - the entry attributes should be appended to this string
+*/
+void CDirRegion::CreateAndWriteCurrentDirEntry(unsigned int aCurClusterNumber,string& aString)
+{
+	iCurEntryClusterNumber = aCurClusterNumber;
+	CDirectory* currentDirectory = new CDirectory(".",NULL);
+
+	currentDirectory->SetEntryAttribute(EAttrDirectory);
+	currentDirectory->SetClusterNumberLow((unsigned short) (iCurEntryClusterNumber & KHighWordMask));
+	currentDirectory->SetClusterNumberHi((unsigned short) (iCurEntryClusterNumber >> KBitShift16));
+
+	TShortDirEntry entry ;
+    currentDirectory->GetShortEntry(entry);
+    aString.append((const char*)(&entry),sizeof(entry));
+	iCurrentDirEntry = true;
+	delete currentDirectory;
+	currentDirectory = NULL;
+}
+
+/**
+Function responsible to push the directory entry clusters into cluster MAP only if the
+directory entry string size is greater than the cluster size.
+
+@internalComponent
+@released
+
+@param aNumber - is the Cluster Key used to insert the cluster into cluster map
+@param aString - is the directory entry string
+@param aClustersRequired - No of clusters required to hold this string
+*/
+
+void CDirRegion::PushDirectoryEntryString(unsigned int aNumber,string& aString,int aClustersRequired)
+{
+	int clusterCount = 0;
+	int clusterKey = aNumber;
+	iClusterPtr->CreateMap(aNumber,clusterKey);
+	iClusterMap[clusterKey] =	aString.substr(clusterCount*iClusterSize,iClusterSize);
+	++clusterCount;
+	string clusterSizeString;
+	for(; clusterCount < aClustersRequired; ++clusterCount)
+	{
+		clusterKey = iClusterPtr->GetCurrentClusterNumber();
+		clusterSizeString = aString.substr(clusterCount*iClusterSize,iClusterSize);
+		clusterSizeString.append((iClusterSize - clusterSizeString.length()),0);
+		iClusterMap[clusterKey] = clusterSizeString;
+		iClusterPtr->CreateMap(aNumber,clusterKey);
+		iClusterPtr->UpdateNextAvailableClusterNumber();
+	}
+}
+
+/**Function responsible to 
+1. Convert the string into equal size clusters of cluster size
+2. Insert the clusters into Cluster MAP
+
+@internalComponent
+@released
+
+@param aNumber - cluster number, used to map the cluster
+@param aString - reference of input string
+@param aClusterSize - used to split the string
+@param aAttribute - current entry attribute
+*/
+void CDirRegion::PushStringIntoClusterMap(unsigned int aNumber, string& aString, unsigned long int aClusterSize,char aAttribute)
+{
+	int receivedStringLength = aString.length();
+	/* Precaution, once the map is initialized with specific cluster number don't over write
+	 * it once again. Look for the cluster number within the existing MAP and then proceed with 
+	 * filling in the cluster.
+	 */
+	StringMap::iterator iter= iClusterMap.find(aNumber);
+	if(iter == iClusterMap.end())
+	{
+		/* The length of the cluster content (aString) can be more or less than the cluster size, 
+		 * hence, calculate the total number of clusters required.
+		 */
+		int clustersRequired = receivedStringLength / aClusterSize;
+		if((receivedStringLength % aClusterSize) > 0)
+		{
+			++clustersRequired;
+		}
+		if((clustersRequired > 1) && (aAttribute == EAttrDirectory))
+		{
+			PushDirectoryEntryString(aNumber,aString,clustersRequired);
+			return;
+		}
+		int updatedClusterNumber = aNumber;
+		string clusterSizeString;
+		for(short int clusterCount = 0; clusterCount < clustersRequired; ++clusterCount)
+		{
+			/* In case of the contents occupying more than one cluster, break the contents into
+			 * multiple parts, each one measuring as that of the cluster size.
+			 */
+			clusterSizeString = aString.substr(clusterCount * aClusterSize,aClusterSize);
+			iClusterPtr->CreateMap(aNumber,updatedClusterNumber);
+			if(clusterSizeString.length() < aClusterSize)
+			{
+				/* Copied string size is less than cluster size, fill the remaining space
+				 * with zero
+				 */
+				clusterSizeString.append((aClusterSize - clusterSizeString.length()),0);
+			}
+			// Insert the string into ClusterMap	
+			iClusterMap[updatedClusterNumber] = clusterSizeString;
+		
+			iClusterPtr->UpdateNextAvailableClusterNumber();
+			updatedClusterNumber = iClusterPtr->GetCurrentClusterNumber ();
+		}
+		/* In the above loop, cluster number is incremented to point to the next entry.
+		 * However, before writing a directory or a volume id entry, it is always ensured 
+		 * to get the next cluster number. Hence in this case, it is required to decrement
+		 * the cluster number, so that the pointer points to the end of the cluster occupied.
+		 */
+		if(aAttribute == EAttrDirectory || aAttribute == EAttrVolumeId)
+		{
+			iClusterPtr->DecrementCurrentClusterNumber ();
+		}
+	}
+}
+
+/**
+Function is responsible to take in the tree structured directory 
+information and to initialize the starting cluster in the Cluster Map.
+
+@internalComponent
+@released
+
+@param aNodeList - the list which holds root entry
+*/
+void CDirRegion::CheckEntry(EntryList aNodeList)
+{
+	if(aNodeList.size() > 0)
+	{
+		if(iRootDirSizeInBytes > 0)
+		{
+			//FAT16 Root entries are written into Cluster 1
+			iClusterKey = KFat16RootEntryNumber;
+		}
+		else
+		{
+			//FAT32 Root entries are written into Cluster 2			
+			iClusterPtr->UpdateNextAvailableClusterNumber();
+			iClusterKey = KFat32RootEntryNumber; 
+		}
+		if(aNodeList.front()->GetEntryList()->size() <= 0)
+		{
+			throw ErrorHandler(NOENTRIESFOUND, __FILE__, __LINE__);
+		}
+	}
+	else
+	{
+		throw ErrorHandler(ROOTNOTFOUND, __FILE__, __LINE__);
+	}
+}
+
+/**
+Function receives Tree structured folder information and does the following:
+1. Generates Directory Entry portion of FAT image recursively.
+2. If it finds the entry as file then writes its contents.
+3. If the entry is long name then longfilename class invoked to create long entries.
+
+@internalComponent
+@released
+
+@param aEntry  - Subdirectory pointer of root directory
+@param aParentDirClusterNumber - parent directory cluster number
+*/
+void CDirRegion::CreateDirEntry(CDirectory* aEntry,unsigned int aParentDirClusterNumber)
+{
+	unsigned int currentDirClusterNumber = 0;
+	int rootClusterSize = 0;
+	if(iFirstCluster == true)
+	{
+			iCurrentDirEntry = true;
+			iParentDirEntry = true;
+			/**Root directory and Normal directory has one difference.
+			FAT16 : Root cluster occupies 32 sectors
+			FAT32 : Root cluster occupies only one cluster
+			*/
+			rootClusterSize = (iRootDirSizeInBytes > 0)?iRootDirSizeInBytes:iClusterSize; 
+	}
+	else
+	{
+		currentDirClusterNumber = Get32BitClusterNumber(aEntry->GetClusterNumberHi(),
+														aEntry->GetClusterNumberLow());
+	}
+	
+	//printIterator used while printing the entries
+	EntryList::iterator printIterator = aEntry->GetEntryList()->begin(); 
+	//traverseIterator used during recursive call
+	EntryList::iterator traverseIterator = printIterator;
+	
+	unsigned int dirEntryCount = aEntry->GetEntryList()->size();
+
+	string dirString;
+	string nameString;
+	CDirectory* tempDirEntry = (*printIterator);
+	list<TLongDirEntry> longNames ; 
+	//Writes all the Directory entries available in one Directory entry
+	while(dirEntryCount > 0)
+	{
+		tempDirEntry = (*printIterator);
+		
+		tempDirEntry->SetClusterNumberHi(iClusterPtr->GetHighWordClusterNumber());
+		tempDirEntry->SetClusterNumberLow(iClusterPtr->GetLowWordClusterNumber());
+
+		/* Every directory should have current and parent directory entries in its
+		 * respective cluster. Hence Create the current and parent directory entries 
+		 * only if it is not created already.
+		 */
+		if(!iCurrentDirEntry && !iParentDirEntry)
+		{
+			CreateAndWriteCurrentDirEntry(currentDirClusterNumber,dirString);
+			iClusterKey = currentDirClusterNumber;
+			CreateAndWriteParentDirEntry(aParentDirClusterNumber,dirString);
+		}
+		MessageHandler::ReportMessage(INFORMATION,
+									  ENTRYCREATEMSG,
+									  (char*)tempDirEntry->GetEntryName().c_str()); 
+									  
+		if(tempDirEntry->GetLongEntries(longNames)){ 
+			list<TLongDirEntry>::const_iterator i = longNames.begin();
+			while(i != longNames.end()) {
+				dirString.append((char*)(&(*i)),sizeof(TLongDirEntry)); 
+				i++ ;
+			} 
+		}
+		TShortDirEntry shortEntry ;
+		tempDirEntry->GetShortEntry(shortEntry);	 
+		dirString.append((char*)(&shortEntry),sizeof(TShortDirEntry));		 
+		if(tempDirEntry->IsFile())
+		{
+			WriteFileDataInToCluster(tempDirEntry);
+		}
+		else
+		{
+			iClusterPtr->UpdateNextAvailableClusterNumber ();
+			//tempDirEntry->SetEntryAttribute(tempDirEntry->GetEntryAttribute() | EAttrDirectory);
+		}
+		++printIterator;
+		--dirEntryCount;
+	}
+
+	iCurrentDirEntry = false;
+	iParentDirEntry = false;
+	aParentDirClusterNumber = currentDirClusterNumber;
+	if(iFirstCluster == true)
+	{
+		PushStringIntoClusterMap(iClusterKey,dirString,rootClusterSize,aEntry->GetEntryAttribute());
+		iFirstCluster = false;
+	}
+	else
+	{
+		PushStringIntoClusterMap(iClusterKey,dirString,iClusterSize,aEntry->GetEntryAttribute());
+	}
+
+	dirEntryCount = aEntry->GetEntryList()->size();
+
+	//Recursive algorithm to print all entries
+	while(dirEntryCount > 0)
+	{
+		if(aEntry->GetEntryList()->size() > 0)
+		{		
+			CreateDirEntry((*traverseIterator),aParentDirClusterNumber);
+		}
+		--dirEntryCount;
+		//if no entries found don't go deep
+		if(dirEntryCount > 0)
+		{
+			aEntry = (*++traverseIterator);
+		}
+	}
+}
+
+/**
+Function responsible to convert two 16 bit words into single 32 bit integer
+
+@internalComponent
+@released
+
+@param aHighWord - 16 bit high word
+@param aLowWord - 16 bit low word
+@return returns the 32 bit integer
+*/
+unsigned int CDirRegion::Get32BitClusterNumber(unsigned int aHighWord, unsigned int aLowWord)
+{
+	unsigned int clusterNumber = aHighWord;
+	clusterNumber <<= KBitShift16;
+	clusterNumber |= aLowWord;
+	return clusterNumber;
+}
--- a/imgtools/imglib/filesystem/source/errorhandler.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/source/errorhandler.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,102 +1,102 @@
-/*
-* 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: 
-* ErrorHandler class receives the message index and the message.
-* Formats the error message using MessageHandler then writes the
-* same into the log file and standard output.
-* @internalComponent
-* @released
-*
-*/
-
-#include "errorhandler.h"
-#include "messagehandler.h"
-
-char *errMssgPrefix="FileSystem : Error:";
-char *Gspace=" ";
-
-/**
-ErrorHandler constructor for doing common thing required for derived 
-class functions.
-
-In some error conditions aSubMessage is required to be passed. So overloaded 
-constructor used here.
-
-@internalComponent
-@released
-
-@param aMessageIndex - Message Index
-@param aSubMessage - Should be displayed  with original message
-@param aFileName - File name from where the error is thrown
-@param aLineNumber - Line number from where the error is thrown
-*/
-ErrorHandler::ErrorHandler(int aMessageIndex, char* aSubMessage, char* aFileName, int aLineNumber)
-                            :iSubMessage(aSubMessage), iFileName(aFileName), iLineNumber(aLineNumber)
-{
-	iMessageIndex = aMessageIndex;
-	iMessage = errMssgPrefix;
-	iMessage += Gspace;
-}
-
-/**
-ErrorHandler constructor for doing common thing required for derived 
-class functions.
-
-@internalComponent
-@released
-
-@param aMessageIndex - Message Index
-@param aFileName - File name from where the error is thrown
-@param aLineNumber - Line number from where the error is thrown
-*/
-ErrorHandler::ErrorHandler(int aMessageIndex, char* aFileName, int aLineNumber)
-                            : iFileName(aFileName), iLineNumber(aLineNumber)
-{
-	iMessageIndex = aMessageIndex;
-	iMessage = errMssgPrefix;
-	iMessage += Gspace;
-}
-
-/**
-ErrorHandler destructor.
-
-@internalComponent
-@released
-*/
-ErrorHandler::~ErrorHandler()
-{
-	MessageHandler::CleanUp();
-}
-
-/**
-Function to report the error
-
-@internalComponent
-@released
-*/
-void ErrorHandler::Report()
-{
-	char *tempMssg;
-	char *errMessage;
-
-	errMessage=MessageHandler::GetInstance()->GetMessageString(iMessageIndex);
-	if(errMessage)
-	{
-		tempMssg = new char[strlen(errMessage) + strlen(iFileName.c_str()) + sizeof(int) + strlen(iSubMessage.c_str())];
-		sprintf(tempMssg, errMessage, iFileName.c_str(), iLineNumber, iSubMessage.c_str());
-		iMessage += tempMssg;
-		MessageHandler::GetInstance()->Output(iMessage.c_str());
-		delete[] tempMssg;
-	}
-}
+/*
+* 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: 
+* ErrorHandler class receives the message index and the message.
+* Formats the error message using MessageHandler then writes the
+* same into the log file and standard output.
+* @internalComponent
+* @released
+*
+*/
+
+#include "errorhandler.h"
+#include "messagehandler.h"
+
+char *errMssgPrefix="FileSystem : Error:";
+char *Gspace=" ";
+
+/**
+ErrorHandler constructor for doing common thing required for derived 
+class functions.
+
+In some error conditions aSubMessage is required to be passed. So overloaded 
+constructor used here.
+
+@internalComponent
+@released
+
+@param aMessageIndex - Message Index
+@param aSubMessage - Should be displayed  with original message
+@param aFileName - File name from where the error is thrown
+@param aLineNumber - Line number from where the error is thrown
+*/
+ErrorHandler::ErrorHandler(int aMessageIndex, char* aSubMessage, char* aFileName, int aLineNumber)
+                            :iSubMessage(aSubMessage), iFileName(aFileName), iLineNumber(aLineNumber)
+{
+	iMessageIndex = aMessageIndex;
+	iMessage = errMssgPrefix;
+	iMessage += Gspace;
+}
+
+/**
+ErrorHandler constructor for doing common thing required for derived 
+class functions.
+
+@internalComponent
+@released
+
+@param aMessageIndex - Message Index
+@param aFileName - File name from where the error is thrown
+@param aLineNumber - Line number from where the error is thrown
+*/
+ErrorHandler::ErrorHandler(int aMessageIndex, char* aFileName, int aLineNumber)
+                            : iFileName(aFileName), iLineNumber(aLineNumber)
+{
+	iMessageIndex = aMessageIndex;
+	iMessage = errMssgPrefix;
+	iMessage += Gspace;
+}
+
+/**
+ErrorHandler destructor.
+
+@internalComponent
+@released
+*/
+ErrorHandler::~ErrorHandler()
+{
+	MessageHandler::CleanUp();
+}
+
+/**
+Function to report the error
+
+@internalComponent
+@released
+*/
+void ErrorHandler::Report()
+{
+	char *tempMssg;
+	char *errMessage;
+
+	errMessage=MessageHandler::GetInstance()->GetMessageString(iMessageIndex);
+	if(errMessage)
+	{
+		tempMssg = new char[strlen(errMessage) + iFileName.length() + sizeof(int) + iSubMessage.length()];
+		sprintf(tempMssg, errMessage, iFileName.c_str(), iLineNumber, iSubMessage.c_str());
+		iMessage += tempMssg;
+		MessageHandler::GetInstance()->Output(iMessage.c_str());
+		delete[] tempMssg;
+	}
+}
--- a/imgtools/imglib/filesystem/source/fat16filesystem.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/source/fat16filesystem.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,318 +1,318 @@
-/*
-* 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: 
-* CFat16FileSystem is the concrete class which is responsible for 
-* creating a FAT16 image. This class constitutes the method to 
-* create boot sector, FAT Table and data region of a FAT16 Image
-* @internalComponent
-* @released
-*
-*/
-
-#include"fat16filesystem.h"
-
-
-/**
-Initializes the boot sector of a FAT 16 volume
-
-@internalComponent
-@released
-
-@param aPartitionSize partition size in bytes
-@param aConfigurableFatAttributes ConfigurableFatAttributes
-*/
-void CFat16FileSystem::CreateBootSector(Long64 aPartitionSize,ConfigurableFatAttributes* aConfigurableFatAttributes)
-{
- 	iFAT16BootSector.SetOEMName();
-	unsigned char* OEMName = iFAT16BootSector.OEMName();
-	iFAT16BootSector.SetJumpInstruction();
-	unsigned char* JmpBoot = iFAT16BootSector.JumpInstruction();
-	iFAT16BootSector.SetBytesPerSector(aConfigurableFatAttributes->iDriveSectorSize);
-	unsigned short BytesPerSector = (unsigned short)iFAT16BootSector.BytesPerSector();
-	iFAT16BootSector.ComputeSectorsPerCluster(aPartitionSize);
-	unsigned char SectorsPerCluster = iFAT16BootSector.SectorsPerCluster();
-	iFAT16BootSector.SetReservedSectors();
-	unsigned short ReservedSectors = iFAT16BootSector.ReservedSectors();
-	iFAT16BootSector.SetNumberOfFats(aConfigurableFatAttributes->iDriveNoOfFATs);
-	unsigned char NumFats = iFAT16BootSector.NumberOfFats();
-	iFAT16BootSector.SetRootDirEntries();
-	unsigned short RootDirEntries = iFAT16BootSector.RootDirEntries();
-	iFAT16BootSector.ComputeTotalSectors(aPartitionSize);
-	unsigned short LowSectors = iFAT16BootSector.LowSectorsCount();
-	iFAT16BootSector.SetMedia();
-	unsigned char Media = iFAT16BootSector.Media();
-	iFAT16BootSector.ComputeFatSectors(aPartitionSize);
-	unsigned short FatSectors = iFAT16BootSector.FatSectors();
-	iFAT16BootSector.SetSectorsPerTrack();
-	unsigned short SectorPerTrack = iFAT16BootSector.SectorsPerTrack();
-	iFAT16BootSector.SetNumberOfHeads();
-	unsigned short NumberOfHeads = iFAT16BootSector.NumberOfHeads();
-	iFAT16BootSector.SetHiddenSectors();
-	unsigned int HiddenSectors = iFAT16BootSector.HiddenSectors();
-	unsigned int HighSectorsCount = iFAT16BootSector.HighSectorsCount();
-	iFAT16BootSector.SetBootSectorDriveNumber();
-	unsigned char BootSectorDriveNumber = iFAT16BootSector.BootSectorDriveNumber();
-	iFAT16BootSector.SetReservedByte();
-	unsigned char ReservedByte = iFAT16BootSector.ReservedByte();
-	iFAT16BootSector.SetBootSignature();
-	unsigned char BootSignature = iFAT16BootSector.BootSignature();
-	iFAT16BootSector.SetVolumeId();
-	unsigned int VolumeId = iFAT16BootSector.VolumeId();
-	iFAT16BootSector.SetVolumeLab(aConfigurableFatAttributes->iDriveVolumeLabel);
-	unsigned char* VolumeLab = iFAT16BootSector.VolumeLab();
-	iFAT16BootSector.SetFileSysType();
-	unsigned char* FileSysType = iFAT16BootSector.FileSysType();
-	//copying of boot sector values in to the array
-	iData = new unsigned char[BytesPerSector];
-	unsigned int pos = 0;
-	memcpy(&iData[pos],JmpBoot,3);
-	pos += 3;
-	memcpy(&iData[pos],OEMName,8);
-	pos += 8;
-	memcpy(&iData[pos],&BytesPerSector,2);
-	pos += 2;
-	memcpy(&iData[pos],&SectorsPerCluster,1);
-	pos += 1;
-	memcpy(&iData[pos],&ReservedSectors,2);
-	pos += 2;
-	memcpy(&iData[pos],&NumFats,1);
-	pos += 1;
-	memcpy(&iData[pos],&RootDirEntries,2);
-	pos += 2;
-	memcpy(&iData[pos],&LowSectors,2);
-	pos += 2;
-	memcpy(&iData[pos],&Media,1);
-	pos += 1;
-	memcpy(&iData[pos],&FatSectors,2);
-	pos += 2;
-	memcpy(&iData[pos],&SectorPerTrack,2);
-	pos += 2;
-	memcpy(&iData[pos],&NumberOfHeads,2);
-	pos += 2;
-	memcpy(&iData[pos],&HiddenSectors,4);
-	pos += 4;
-	memcpy(&iData[pos],&HighSectorsCount,4);
-	pos += 4;
-	memcpy(&iData[pos],&BootSectorDriveNumber,1);		
-	pos += 1;
-	memcpy(&iData[pos],&ReservedByte,1);
-	pos += 1;
-	memcpy(&iData[pos],&BootSignature,1);
-	pos += 1;
-	memcpy(&iData[pos],&VolumeId,4);
-	pos += 4;
-	memcpy(&iData[pos],VolumeLab,11);
-	pos += 11;
-	memcpy(&iData[pos],FileSysType,8);
-	pos += 8;
-	while(pos < BytesPerSector)
-	{
-		iData[pos] = 0;
-		pos++;
-	}
-	// Set sector [510] as 0xAA and [511] as 0x55 to mark the end of boot sector
-	iData[KSizeOfFatBootSector-2] = 0x55;
-	iData[KSizeOfFatBootSector-1] = 0xAA;
-	// It is perfectly ok for the last two bytes of the boot sector to also 
-	// have the signature 0xAA55.
-	iData[BytesPerSector-2] = 0x55;
-	iData[BytesPerSector-1] = 0xAA;
-
-
-	ComputeClusterSizeInBytes();
-	ComputeRootDirSectors();
-	ComputeBytesPerSector();
-	MessageHandler::ReportMessage (INFORMATION,BOOTSECTORCREATEMSG, "FAT16");
-}
-
-/**
-Writes the boot sector of a FAT 16 volume
-@param aOutPutStream handle to file stream	
-
-@internalComponent
-@released
-*/
-void CFat16FileSystem::WriteBootSector(ofstream& aOutPutStream)
-{
-	MessageHandler::ReportMessage (INFORMATION,BOOTSECTORWRITEMSG,"FAT16");
-	aOutPutStream.write(reinterpret_cast<char*>(&iData[0]),iFAT16BootSector.BytesPerSector());
-	aOutPutStream.flush();
-}
-/**
-Creates the FAT Table
-
-@internalComponent
-@released
-
-@param ofstream
-*/
-void CFat16FileSystem::CreateFatTable(ofstream& aOutPutStream)
-{
-	int FATSizeInBytes = (iFAT16BootSector.FatSectors()) * (iFAT16BootSector.BytesPerSector());
-	// Each FAT16 entries occupies 2 bytes, hence divided by 2
-	unsigned int totalFatEntries = FATSizeInBytes / 2;
-	unsigned short *FatTable = new unsigned short[totalFatEntries];
-	unsigned short int clusterCounter = 1;
-	int previousCluster;
-	FatTable[0] = KFat16FirstEntry;
-	/**Say cluster 5 starts at 5 and occupies clusters 7 and 9. The FAT table should have the 
-	value 7 at	cluster location 5, the value 9 at cluster 7 and 'eof' value at cluster 9.
-	Below algorithm serves this algorithm
-	*/
-	Iterator itr = iClustersPerEntry->begin();
-	while(itr != iClustersPerEntry->end())
-	{
-		previousCluster = itr->second;
-		if(iClustersPerEntry->count(itr->first) > 1)
-		{
-			for(unsigned int i = 1; i < iClustersPerEntry->count(itr->first); i++)
-			{
-				FatTable[previousCluster] = (unsigned short)(++itr)->second;
-				previousCluster = itr->second;
-				++clusterCounter;
-			}
-		}
-		FatTable[previousCluster] = EOF16;
-		itr++;
-		++clusterCounter;
-	}
-	// Each FAT16 entries occupies 2 bytes, hence multiply by 2
-	std::string aFatString(reinterpret_cast<char*>(FatTable),clusterCounter*2);
-	delete[] FatTable;
-	if(clusterCounter < totalFatEntries)
-	{
-		// Each FAT16 entries occupies 2 bytes, hence multiply by 2
-		aFatString.append((totalFatEntries - clusterCounter)*2, 0);
-	}
-	MessageHandler::ReportMessage (INFORMATION,FATTABLEWRITEMSG,
-								   "FAT16");
-	
-	// Write FAT table multiple times depending upon the No of FATS set.
-	unsigned int noOfFats = iFAT16BootSector.NumberOfFats();
-	for(unsigned int i=0; i<noOfFats; i++)
-	{
-		aOutPutStream.write(aFatString.c_str(),aFatString.length());
-	}
-	
-	aFatString.erase();
-	aOutPutStream.flush();
-}
-
-/**
-set the cluster size in bytes,iClusterSize
-
-@internalComponent
-@released
-*/
-void CFat16FileSystem::ComputeClusterSizeInBytes()
-{
-	iClusterSize = (iFAT16BootSector.SectorsPerCluster()) * (iFAT16BootSector.BytesPerSector());
-}
-
-/**
-set the count of sectors occupied by the root directory,iRootDirSectors.
-
-@internalComponent
-@released
-*/
-void CFat16FileSystem::ComputeRootDirSectors()
-{
-	iRootDirSectors = (iFAT16BootSector.RootDirEntries() * (KDefaultRootDirEntrySize) + 
-					  (iFAT16BootSector.BytesPerSector() - 1)) / iFAT16BootSector.BytesPerSector();
-}	
-
-/**
-Initialize the Bytes per Sector variable value.
-
-@internalComponent
-@released
-*/
-void CFat16FileSystem::ComputeBytesPerSector()
-{
-	iBytesPerSector = iFAT16BootSector.BytesPerSector();
-}
-
-
-/**
-Compute the total number of clusters in Data segment of the FAT volume
-
-@internalComponent
-@released
-*/
-void CFat16FileSystem::ComputeTotalClusters(Long64 aPartitionSize)
-{
-	unsigned long int iTotalDataSectors = iFAT16BootSector.TotalSectors(aPartitionSize) - 
-										  ((iFAT16BootSector.NumberOfFats() * iFAT16BootSector.FatSectors()) + 
-										  iRootDirSectors + iFAT16BootSector.ReservedSectors());
-	iTotalClusters = iTotalDataSectors / iFAT16BootSector.SectorsPerCluster();
-	if(iTotalClusters < KMinimumFat16Clusters)
-	{
-		throw ErrorHandler(BOOTSECTORERROR,"Low Partition Size",__FILE__,__LINE__);
-	}
-	if(iTotalClusters > KMaximumFat16Clusters)
-	{
-		throw ErrorHandler(BOOTSECTORERROR,"High Partition Size",__FILE__,__LINE__);
-	}
-	
-}
-
-/**
-This methods encapsulates the function call to write a complete FAT16 Image
-
-@internalComponent
-@released
-
-@param aPartitionSize partition size in bytes
-@param aNodeList Directory structure 
-@param aOutPutStream output stream for writing file image
-@param aImageFileName image file name 
-@param aLogFileName log file name 
-@param aConfigurableFatAttributes ConfigurableFatAttributes
-*/
-
-void CFat16FileSystem::Execute(Long64 aPartitionSize,EntryList aNodeList,ofstream& aOutPutStream,
-							   ConfigurableFatAttributes* aConfigurableFatAttributes)
-{
-	CDirRegion* dirRegionPtr = NULL;
-	try
-	{
-		CreateBootSector(aPartitionSize,aConfigurableFatAttributes);
-		ComputeTotalClusters(aPartitionSize);
-		WriteBootSector(aOutPutStream);
-		dirRegionPtr = new CDirRegion(aNodeList,this);
-		dirRegionPtr->Execute();
-		iClustersPerEntry = dirRegionPtr->GetClustersPerEntryMap();
-		CreateFatTable(aOutPutStream);
-		dirRegionPtr ->WriteClustersIntoFile(aOutPutStream);
-		delete dirRegionPtr ;
-	}
-	catch(ErrorHandler &aError)
-	{
-		delete dirRegionPtr;
-		//Re throw the same error message
-		throw ErrorHandler(aError.iMessageIndex,(char*)aError.iSubMessage.c_str(),(char*)aError.iFileName.c_str(),aError.iLineNumber);
-	}
-	/**
-	Irrespective of successful or unsuccessful data drive image generation ROFSBUILD
-	may try to generate images for successive ".oby" file input.
-	During this course unhandled exceptions may cause leaving some memory on heap 
-	unused. so the unhandled exceptions handling is used to free the memory allocated 
-	on heap. 
-	*/
-	catch(...)
-	{
-		delete dirRegionPtr;
-		throw ErrorHandler(UNKNOWNERROR, __FILE__, __LINE__);
-	}
-}
+/*
+* 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: 
+* CFat16FileSystem is the concrete class which is responsible for 
+* creating a FAT16 image. This class constitutes the method to 
+* create boot sector, FAT Table and data region of a FAT16 Image
+* @internalComponent
+* @released
+*
+*/
+
+#include"fat16filesystem.h"
+
+
+/**
+Initializes the boot sector of a FAT 16 volume
+
+@internalComponent
+@released
+
+@param aPartitionSize partition size in bytes
+@param aConfigurableFatAttributes ConfigurableFatAttributes
+*/
+void CFat16FileSystem::CreateBootSector(Long64 aPartitionSize,ConfigurableFatAttributes* aConfigurableFatAttributes)
+{
+ 	iFAT16BootSector.SetOEMName();
+	unsigned char* OEMName = iFAT16BootSector.OEMName();
+	iFAT16BootSector.SetJumpInstruction();
+	unsigned char* JmpBoot = iFAT16BootSector.JumpInstruction();
+	iFAT16BootSector.SetBytesPerSector(aConfigurableFatAttributes->iDriveSectorSize);
+	unsigned short BytesPerSector = (unsigned short)iFAT16BootSector.BytesPerSector();
+	iFAT16BootSector.ComputeSectorsPerCluster(aPartitionSize);
+	unsigned char SectorsPerCluster = iFAT16BootSector.SectorsPerCluster();
+	iFAT16BootSector.SetReservedSectors();
+	unsigned short ReservedSectors = iFAT16BootSector.ReservedSectors();
+	iFAT16BootSector.SetNumberOfFats(aConfigurableFatAttributes->iDriveNoOfFATs);
+	unsigned char NumFats = iFAT16BootSector.NumberOfFats();
+	iFAT16BootSector.SetRootDirEntries();
+	unsigned short RootDirEntries = iFAT16BootSector.RootDirEntries();
+	iFAT16BootSector.ComputeTotalSectors(aPartitionSize);
+	unsigned short LowSectors = iFAT16BootSector.LowSectorsCount();
+	iFAT16BootSector.SetMedia();
+	unsigned char Media = iFAT16BootSector.Media();
+	iFAT16BootSector.ComputeFatSectors(aPartitionSize);
+	unsigned short FatSectors = iFAT16BootSector.FatSectors();
+	iFAT16BootSector.SetSectorsPerTrack();
+	unsigned short SectorPerTrack = iFAT16BootSector.SectorsPerTrack();
+	iFAT16BootSector.SetNumberOfHeads();
+	unsigned short NumberOfHeads = iFAT16BootSector.NumberOfHeads();
+	iFAT16BootSector.SetHiddenSectors();
+	unsigned int HiddenSectors = iFAT16BootSector.HiddenSectors();
+	unsigned int HighSectorsCount = iFAT16BootSector.HighSectorsCount();
+	iFAT16BootSector.SetBootSectorDriveNumber();
+	unsigned char BootSectorDriveNumber = iFAT16BootSector.BootSectorDriveNumber();
+	iFAT16BootSector.SetReservedByte();
+	unsigned char ReservedByte = iFAT16BootSector.ReservedByte();
+	iFAT16BootSector.SetBootSignature();
+	unsigned char BootSignature = iFAT16BootSector.BootSignature();
+	iFAT16BootSector.SetVolumeId();
+	unsigned int VolumeId = iFAT16BootSector.VolumeId();
+	iFAT16BootSector.SetVolumeLab(aConfigurableFatAttributes->iDriveVolumeLabel);
+	unsigned char* VolumeLab = iFAT16BootSector.VolumeLab();
+	iFAT16BootSector.SetFileSysType();
+	unsigned char* FileSysType = iFAT16BootSector.FileSysType();
+	//copying of boot sector values in to the array
+	iData = new unsigned char[BytesPerSector];
+	unsigned int pos = 0;
+	memcpy(&iData[pos],JmpBoot,3);
+	pos += 3;
+	memcpy(&iData[pos],OEMName,8);
+	pos += 8;
+	memcpy(&iData[pos],&BytesPerSector,2);
+	pos += 2;
+	memcpy(&iData[pos],&SectorsPerCluster,1);
+	pos += 1;
+	memcpy(&iData[pos],&ReservedSectors,2);
+	pos += 2;
+	memcpy(&iData[pos],&NumFats,1);
+	pos += 1;
+	memcpy(&iData[pos],&RootDirEntries,2);
+	pos += 2;
+	memcpy(&iData[pos],&LowSectors,2);
+	pos += 2;
+	memcpy(&iData[pos],&Media,1);
+	pos += 1;
+	memcpy(&iData[pos],&FatSectors,2);
+	pos += 2;
+	memcpy(&iData[pos],&SectorPerTrack,2);
+	pos += 2;
+	memcpy(&iData[pos],&NumberOfHeads,2);
+	pos += 2;
+	memcpy(&iData[pos],&HiddenSectors,4);
+	pos += 4;
+	memcpy(&iData[pos],&HighSectorsCount,4);
+	pos += 4;
+	memcpy(&iData[pos],&BootSectorDriveNumber,1);		
+	pos += 1;
+	memcpy(&iData[pos],&ReservedByte,1);
+	pos += 1;
+	memcpy(&iData[pos],&BootSignature,1);
+	pos += 1;
+	memcpy(&iData[pos],&VolumeId,4);
+	pos += 4;
+	memcpy(&iData[pos],VolumeLab,11);
+	pos += 11;
+	memcpy(&iData[pos],FileSysType,8);
+	pos += 8;
+	while(pos < BytesPerSector)
+	{
+		iData[pos] = 0;
+		pos++;
+	}
+	// Set sector [510] as 0xAA and [511] as 0x55 to mark the end of boot sector
+	iData[KSizeOfFatBootSector-2] = 0x55;
+	iData[KSizeOfFatBootSector-1] = 0xAA;
+	// It is perfectly ok for the last two bytes of the boot sector to also 
+	// have the signature 0xAA55.
+	iData[BytesPerSector-2] = 0x55;
+	iData[BytesPerSector-1] = 0xAA;
+
+
+	ComputeClusterSizeInBytes();
+	ComputeRootDirSectors();
+	ComputeBytesPerSector();
+	MessageHandler::ReportMessage (INFORMATION,BOOTSECTORCREATEMSG, "FAT16");
+}
+
+/**
+Writes the boot sector of a FAT 16 volume
+@param aOutPutStream handle to file stream	
+
+@internalComponent
+@released
+*/
+void CFat16FileSystem::WriteBootSector(ofstream& aOutPutStream)
+{
+	MessageHandler::ReportMessage (INFORMATION,BOOTSECTORWRITEMSG,"FAT16");
+	aOutPutStream.write(reinterpret_cast<char*>(&iData[0]),iFAT16BootSector.BytesPerSector());
+	aOutPutStream.flush();
+}
+/**
+Creates the FAT Table
+
+@internalComponent
+@released
+
+@param ofstream
+*/
+void CFat16FileSystem::CreateFatTable(ofstream& aOutPutStream)
+{
+	int FATSizeInBytes = (iFAT16BootSector.FatSectors()) * (iFAT16BootSector.BytesPerSector());
+	// Each FAT16 entries occupies 2 bytes, hence divided by 2
+	unsigned int totalFatEntries = FATSizeInBytes / 2;
+	unsigned short *FatTable = new unsigned short[totalFatEntries];
+	unsigned short int clusterCounter = 1;
+	int previousCluster;
+	FatTable[0] = KFat16FirstEntry;
+	/**Say cluster 5 starts at 5 and occupies clusters 7 and 9. The FAT table should have the 
+	value 7 at	cluster location 5, the value 9 at cluster 7 and 'eof' value at cluster 9.
+	Below algorithm serves this algorithm
+	*/
+	Iterator itr = iClustersPerEntry->begin();
+	while(itr != iClustersPerEntry->end())
+	{
+		previousCluster = itr->second;
+		if(iClustersPerEntry->count(itr->first) > 1)
+		{
+			for(unsigned int i = 1; i < iClustersPerEntry->count(itr->first); i++)
+			{
+				FatTable[previousCluster] = (unsigned short)(++itr)->second;
+				previousCluster = itr->second;
+				++clusterCounter;
+			}
+		}
+		FatTable[previousCluster] = EOF16;
+		itr++;
+		++clusterCounter;
+	}
+	// Each FAT16 entries occupies 2 bytes, hence multiply by 2
+	string aFatString(reinterpret_cast<char*>(FatTable),clusterCounter*2);
+	delete[] FatTable;
+	if(clusterCounter < totalFatEntries)
+	{
+		// Each FAT16 entries occupies 2 bytes, hence multiply by 2
+		aFatString.append((totalFatEntries - clusterCounter)*2, 0);
+	}
+	MessageHandler::ReportMessage (INFORMATION,FATTABLEWRITEMSG,
+								   "FAT16");
+	
+	// Write FAT table multiple times depending upon the No of FATS set.
+	unsigned int noOfFats = iFAT16BootSector.NumberOfFats();
+	for(unsigned int i=0; i<noOfFats; i++)
+	{
+		aOutPutStream.write(aFatString.c_str(),aFatString.length());
+	}
+	
+	aFatString.erase();
+	aOutPutStream.flush();
+}
+
+/**
+set the cluster size in bytes,iClusterSize
+
+@internalComponent
+@released
+*/
+void CFat16FileSystem::ComputeClusterSizeInBytes()
+{
+	iClusterSize = (iFAT16BootSector.SectorsPerCluster()) * (iFAT16BootSector.BytesPerSector());
+}
+
+/**
+set the count of sectors occupied by the root directory,iRootDirSectors.
+
+@internalComponent
+@released
+*/
+void CFat16FileSystem::ComputeRootDirSectors()
+{
+	iRootDirSectors = (iFAT16BootSector.RootDirEntries() * (KDefaultRootDirEntrySize) + 
+					  (iFAT16BootSector.BytesPerSector() - 1)) / iFAT16BootSector.BytesPerSector();
+}	
+
+/**
+Initialize the Bytes per Sector variable value.
+
+@internalComponent
+@released
+*/
+void CFat16FileSystem::ComputeBytesPerSector()
+{
+	iBytesPerSector = iFAT16BootSector.BytesPerSector();
+}
+
+
+/**
+Compute the total number of clusters in Data segment of the FAT volume
+
+@internalComponent
+@released
+*/
+void CFat16FileSystem::ComputeTotalClusters(Long64 aPartitionSize)
+{
+	unsigned long int iTotalDataSectors = iFAT16BootSector.TotalSectors(aPartitionSize) - 
+										  ((iFAT16BootSector.NumberOfFats() * iFAT16BootSector.FatSectors()) + 
+										  iRootDirSectors + iFAT16BootSector.ReservedSectors());
+	iTotalClusters = iTotalDataSectors / iFAT16BootSector.SectorsPerCluster();
+	if(iTotalClusters < KMinimumFat16Clusters)
+	{
+		throw ErrorHandler(BOOTSECTORERROR,"Low Partition Size",__FILE__,__LINE__);
+	}
+	if(iTotalClusters > KMaximumFat16Clusters)
+	{
+		throw ErrorHandler(BOOTSECTORERROR,"High Partition Size",__FILE__,__LINE__);
+	}
+	
+}
+
+/**
+This methods encapsulates the function call to write a complete FAT16 Image
+
+@internalComponent
+@released
+
+@param aPartitionSize partition size in bytes
+@param aNodeList Directory structure 
+@param aOutPutStream output stream for writing file image
+@param aImageFileName image file name 
+@param aLogFileName log file name 
+@param aConfigurableFatAttributes ConfigurableFatAttributes
+*/
+
+void CFat16FileSystem::Execute(Long64 aPartitionSize,EntryList aNodeList,ofstream& aOutPutStream,
+							   ConfigurableFatAttributes* aConfigurableFatAttributes)
+{
+	CDirRegion* dirRegionPtr = NULL;
+	try
+	{
+		CreateBootSector(aPartitionSize,aConfigurableFatAttributes);
+		ComputeTotalClusters(aPartitionSize);
+		WriteBootSector(aOutPutStream);
+		dirRegionPtr = new CDirRegion(aNodeList,this);
+		dirRegionPtr->Execute();
+		iClustersPerEntry = dirRegionPtr->GetClustersPerEntryMap();
+		CreateFatTable(aOutPutStream);
+		dirRegionPtr ->WriteClustersIntoFile(aOutPutStream);
+		delete dirRegionPtr ;
+	}
+	catch(ErrorHandler &aError)
+	{
+		delete dirRegionPtr;
+		//Re throw the same error message
+		throw ErrorHandler(aError.iMessageIndex,(char*)aError.iSubMessage.c_str(),(char*)aError.iFileName.c_str(),aError.iLineNumber);
+	}
+	/**
+	Irrespective of successful or unsuccessful data drive image generation ROFSBUILD
+	may try to generate images for successive ".oby" file input.
+	During this course unhandled exceptions may cause leaving some memory on heap 
+	unused. so the unhandled exceptions handling is used to free the memory allocated 
+	on heap. 
+	*/
+	catch(...)
+	{
+		delete dirRegionPtr;
+		throw ErrorHandler(UNKNOWNERROR, __FILE__, __LINE__);
+	}
+}
--- a/imgtools/imglib/filesystem/source/fat32filesystem.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/source/fat32filesystem.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,440 +1,440 @@
-/*
-* 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: 
-* CFat32FileSystem is the concrete class which is responsible for 
-* creating a FAT32 image. This class constitutes the method to 
-* create boot sector, FAT Table and data region of a FAT32 Image
-* @internalComponent
-* @released
-*
-*/
-
-#include"fat32filesystem.h"
-
-/**
-Initializes the boot sector of a FAT 32 volume
-
-@internalComponent
-@released
-
-@param aPartitionSize partition size in bytes
-@param aConfigurableFatAttributes ConfigurableFatAttributes
-*/
-void CFat32FileSystem::CreateBootSector(Long64 aPartitionSize,ConfigurableFatAttributes* aConfigurableFatAttributes)
-{
-	//initializes the boot sector values
-	iFAT32BootSector.SetOEMName();
-	unsigned char* OEMName =  iFAT32BootSector.OEMName();
-	iFAT32BootSector.SetJumpInstruction();
-	unsigned char* JmpBoot = iFAT32BootSector.JumpInstruction();
-	iFAT32BootSector.SetBytesPerSector(aConfigurableFatAttributes->iDriveSectorSize);
-	unsigned short BytesPerSector = (unsigned short)iFAT32BootSector.BytesPerSector();
-	iFAT32BootSector.ComputeSectorsPerCluster(aPartitionSize);
-	unsigned char SectorsPerCluster = iFAT32BootSector.SectorsPerCluster();
-	iFAT32BootSector.SetReservedSectors();
-	unsigned short ReservedSectors =  iFAT32BootSector.ReservedSectors();
-	iFAT32BootSector.SetNumberOfFats(aConfigurableFatAttributes->iDriveNoOfFATs);
-	unsigned char NumFats = iFAT32BootSector.NumberOfFats();
-	iFAT32BootSector.SetRootDirEntries();
-	unsigned short RootDirEntries = iFAT32BootSector.RootDirEntries();
-	iFAT32BootSector.ComputeTotalSectors(aPartitionSize);
-	unsigned short LowSectors = iFAT32BootSector.LowSectorsCount();
-	iFAT32BootSector.SetMedia();
-	unsigned char Media = iFAT32BootSector.Media();
-	iFAT32BootSector.ComputeFatSectors(aPartitionSize);
-	unsigned short FatSectors = iFAT32BootSector.FatSectors();
-	iFAT32BootSector.SetSectorsPerTrack();
-	unsigned short SectorPerTrack = iFAT32BootSector.SectorsPerTrack();
-	iFAT32BootSector.SetNumberOfHeads();
-	unsigned short NumberOfHeads = iFAT32BootSector.NumberOfHeads();
-	iFAT32BootSector.SetHiddenSectors();
-	unsigned int HiddenSectors = iFAT32BootSector.HiddenSectors();
-	unsigned int HighSectorsCount = iFAT32BootSector.HighSectorsCount();
-	unsigned int FatSectors32 = iFAT32BootSector.FatSectors32();
-	iFAT32BootSector.SetExtFlags();
-	unsigned short ExtFlags = iFAT32BootSector.ExtFlags();
-	iFAT32BootSector.SetFileSystemVersion();
-	unsigned short FileSystemVersion = iFAT32BootSector.FileSystemVersion();
-	iFAT32BootSector.SetRootCluster();
-	unsigned int RootCluster =  iFAT32BootSector.RootCluster();
-	iFAT32BootSector.SetFSInfo();
-	unsigned short FSInfo  = iFAT32BootSector.FSInfo();
-	iFAT32BootSector.SetBackUpBootSector();
-	unsigned short BackUpBootSector = iFAT32BootSector.BackUpBootSector();
-	iFAT32BootSector.SetFutureReserved();
-	unsigned char* FutureReserved = iFAT32BootSector.FutureReserved();
-	iFAT32BootSector.SetBootSectorDriveNumber();
-	unsigned char BootSectorDriveNumber = iFAT32BootSector.BootSectorDriveNumber();
-	iFAT32BootSector.SetReservedByte();
-	unsigned char ReservedByte = iFAT32BootSector.ReservedByte();
-	iFAT32BootSector.SetBootSignature();
-	unsigned char BootSignature = iFAT32BootSector.BootSignature();
-	iFAT32BootSector.SetVolumeId();
-	unsigned int VolumeId = iFAT32BootSector.VolumeId();
-	iFAT32BootSector.SetVolumeLab(aConfigurableFatAttributes->iDriveVolumeLabel);
-	unsigned char* VolumeLab = iFAT32BootSector.VolumeLab();
-	iFAT32BootSector.SetFileSysType();
-	unsigned char* FileSystemType = iFAT32BootSector.FileSysType();
-
-	//copying of boot sector values in to the array
-	iData = new unsigned char[BytesPerSector];
-	unsigned int pos = 0;
-	memcpy(&iData[pos],JmpBoot,3);
-	pos += 3;
-	memcpy(&iData[pos],OEMName,8);
-	pos += 8;
-	memcpy(&iData[pos],&BytesPerSector,2);
-	pos += 2;
-	memcpy(&iData[pos],&SectorsPerCluster,1);
-	pos += 1;
-	memcpy(&iData[pos],&ReservedSectors,2);
-	pos += 2;
-	memcpy(&iData[pos],&NumFats,1);
-	pos += 1;
-	memcpy(&iData[pos],&RootDirEntries,2);
-	pos += 2;
-	memcpy(&iData[pos],&LowSectors,2);
-	pos += 2;
-	memcpy(&iData[pos],&Media,1);
-	pos += 1;
-	memcpy(&iData[pos],&FatSectors,2);
-	pos += 2;
-	memcpy(&iData[pos],&SectorPerTrack,2);
-	pos += 2;
-	memcpy(&iData[pos],&NumberOfHeads,2);
-	pos += 2;
-	memcpy(&iData[pos],&HiddenSectors,4);
-	pos += 4;
-	memcpy(&iData[pos],&HighSectorsCount,4);
-	pos += 4;
-	memcpy(&iData[pos],&FatSectors32,4);
-	pos += 4;
-	memcpy(&iData[pos],&ExtFlags,2);
-	pos += 2;
-	memcpy(&iData[pos],&FileSystemVersion,2);
-	pos += 2;
-	memcpy(&iData[pos],&RootCluster,4);
-	pos += 4;
-	memcpy(&iData[pos],&FSInfo,2);
-	pos += 2;
-	memcpy(&iData[pos],&BackUpBootSector,2);
-	pos += 2;
-	memcpy(&iData[pos],FutureReserved,12);
-	pos += 12;
-	memcpy(&iData[pos],&BootSectorDriveNumber,1);
-	pos += 1;
-	memcpy(&iData[pos],&ReservedByte,1);
-	pos += 1;
-	memcpy(&iData[pos],&BootSignature,1);
-	pos += 1;
-	memcpy(&iData[pos],&VolumeId,4);
-	pos += 4;
-	memcpy(&iData[pos],VolumeLab,11);
-	pos += 11;
-	memcpy(&iData[pos],FileSystemType,8);
-	pos += 8;
-	while(pos < BytesPerSector)
-	{
-		iData[pos] = 0x00;
-		pos++;
-	}
-	// Set sector [510] as 0xAA and [511] as 0x55 to mark the end of boot sector
-	iData[KSizeOfFatBootSector-2] = 0x55;
-	iData[KSizeOfFatBootSector-1] = 0xAA;
-	// It is perfectly ok for the last two bytes of the boot sector to also 
-	// have the signature 0xAA55.
-	iData[BytesPerSector-2] = 0x55;
-	iData[BytesPerSector-1] = 0xAA;
-	ComputeClusterSizeInBytes();
-	ComputeRootDirSectors();
-	ComputeBytesPerSector();
-	MessageHandler::ReportMessage (INFORMATION,BOOTSECTORCREATEMSG, "FAT32");
-}
-
-/**
-Writes the boot sector of a FAT 32 volume
-
-@internalComponent
-@released
-
-@param aOutPutStream handle for the image file
-*/
-void CFat32FileSystem::WriteBootSector(ofstream& aOutPutStream)
-{
-	MessageHandler::ReportMessage (INFORMATION,BOOTSECTORWRITEMSG, "FAT32");
-	aOutPutStream.write(reinterpret_cast<char*>(&iData[0]),iFAT32BootSector.BytesPerSector());
-	aOutPutStream.flush();
-}
-
-/**
-Creates and writes the FAT Table sector of a FAT 32 volume
-
-@internalComponent
-@released
-
-@param aClustersPerEntryMap iDatastructure containing the mapping of clusters allocated to the file.
-@param aOutPutStream handle for the image file
-*/
-void CFat32FileSystem::CreateFatTable(ofstream& aOutPutStream)
-{
-	//data is written from cluster 2
-	unsigned int clusterCounter = 2;
-	unsigned int FATSizeInBytes = (iFAT32BootSector.FatSectors32()) * (iFAT32BootSector.BytesPerSector());
-	// Each FAT32 entries occupies 4 bytes, hence divided by 4
-	unsigned int totalFatEntries = FATSizeInBytes / 4;
-	//contains the address of FAT Table 	
-	unsigned int *FatTable = new unsigned int[totalFatEntries];
-
-	/**Say cluster 5 starts at 5 and occupies clusters 7 and 9. The FAT table should have the 
-	value 7 at	cluster location 5, the value 9 at cluster 7 and 'eof' value at cluster 9.
-	Below algorithm serves this algorithm
-	*/
-	int previousCluster;
-	FatTable[0] = KFat32FirstEntry;
-	FatTable[1] =  EOF32;
-	Iterator itr = iClustersPerEntry->begin();
-	while(itr !=  iClustersPerEntry->end())
-	{
-		previousCluster = itr->second;
-		if(iClustersPerEntry->count(itr->first) > 1)
-		{
-			for(unsigned int i = 1; i < iClustersPerEntry->count(itr->first); i++)
-			{
-				FatTable[previousCluster] = (++itr)->second;
-				previousCluster = itr->second;
-				++clusterCounter;
-			}
-		}
-		FatTable[previousCluster] = EOF32;
-		itr++;
-		++clusterCounter;
-	}
-	// Each FAT32 entries occupies 4 bytes, hence multiply by 4
-	std::string aFatString(reinterpret_cast<char*>(FatTable),clusterCounter*4);
-	delete[] FatTable;
-	if(clusterCounter < totalFatEntries)
-	{
-		// Each FAT32 entries occupies 4 bytes, hence multiply by 4
-		aFatString.append((totalFatEntries - clusterCounter)*4, 0);
-	}
-	MessageHandler::ReportMessage (INFORMATION,FATTABLEWRITEMSG,
-								   "FAT32");
-	//Write FAT table multiple times depending on the value of No of FATS set.
-	unsigned int noOfFats = iFAT32BootSector.NumberOfFats();
-	for(unsigned int i=0; i<noOfFats; i++)
-	{
-		aOutPutStream.write(aFatString.c_str(),aFatString.length());
-	}
-	aFatString.erase();
-	aOutPutStream.flush();
-}
-
-/**
-FSINfo iData structure specific to FAT32
-
-@internalComponent
-@released
-
-@param aOutPutStream handle for the image file
-*/
-void CFat32FileSystem::CreateFSinfoSector(ofstream& aOutPutStream)
-{
-	int counter = 0;
-	unsigned int bytesPerSector = iFAT32BootSector.BytesPerSector();
-	FSinfoData = new unsigned char[bytesPerSector];
-	iFSInfo.SetFSInfo();
-	memcpy(&FSinfoData[counter], &iFSInfo.FSI_LeadSign,4);
-	counter += 4;
-	memcpy(&FSinfoData[counter], &iFSInfo.FSI_Reserved,480);
-	counter += 480;
-	memcpy(&FSinfoData[counter], &iFSInfo.FSI_StrucSig,4);
-	counter += 4;
-	memcpy(&FSinfoData[counter], &iFSInfo.FSI_Free_Count,4);
-	counter += 4;
-	memcpy(&FSinfoData[counter], &iFSInfo.FSI_Nxt_Free,4);
-	counter += 4;
-	memcpy(&FSinfoData[counter], &iFSInfo.FSI_Reserved2,12);
-	counter += 12;
-	memcpy(&FSinfoData[counter], &iFSInfo.FSI_TrailSig,4);
-	counter += 4;
-	counter += (bytesPerSector-KSizeOfFatBootSector);
-	aOutPutStream.write(reinterpret_cast<char*>(&FSinfoData[0]),counter);
-	aOutPutStream.flush();	
-}
-
-/**
- Initializes the left over reserved sectors of FAT32 image other than boot sector and FSinfo iData sector(sector 0 and 1)
-
- @internalComponent
- @released
-
- @param aOutPutStream handle to file stream		
-*/
-void CFat32FileSystem::RestReservedSectors(ofstream& aOutPutStream)
-{
-	unsigned int bytesPerSector = iFAT32BootSector.BytesPerSector();
-	unsigned char* nullsector = new unsigned char[bytesPerSector];
-	for(unsigned int counter = 0; counter < bytesPerSector ; counter++)
-	{
-		nullsector[counter] = 0;
-	}
-	nullsector[KSizeOfFatBootSector-2] = 0x55;
-	nullsector[KSizeOfFatBootSector-1] = 0xAA;
-	for(unsigned int sectorcount = 2; sectorcount < (unsigned int)(iFAT32BootSector.ReservedSectors()) - 1; sectorcount++)
-	{
-		// Sector no 6 and 7 contains the duplicate copy of boot sector and FSInfo sector in a FAT32 Image
-		if(sectorcount == KBootBackupSector)
-		{
-			aOutPutStream.write(reinterpret_cast<char*>(&iData[0]),bytesPerSector);		
-			aOutPutStream.flush();
-		}
-		if(sectorcount == KFatBackupSector)
-		{
-			aOutPutStream.write(reinterpret_cast<char*>(&FSinfoData[0]),bytesPerSector);		
-			aOutPutStream.flush();
-		}
-		else
-		{
-			aOutPutStream.write(reinterpret_cast<char*>(&nullsector[0]),bytesPerSector);		
-			aOutPutStream.flush();
-		}
-	}
-	delete[] nullsector;
-	nullsector = NULL;
-}
-
-/**
-compute the cluster size in bytes,iClusterSize
-
-@internalComponent
-@released
-*/
-void CFat32FileSystem::ComputeClusterSizeInBytes()
-{
-	iClusterSize = iFAT32BootSector.SectorsPerCluster()*iFAT32BootSector.BytesPerSector();
-}
-
-/**
-Compute the count of sectors occupied by the root directory,iRootDirSectors.
-
-@internalComponent
-@released
-*/
-void CFat32FileSystem::ComputeRootDirSectors()
-{
-	iRootDirSectors = (iFAT32BootSector.RootDirEntries() * (KDefaultRootDirEntrySize) + 
-		              (iFAT32BootSector.BytesPerSector() - 1)) / iFAT32BootSector.BytesPerSector();
-}
-
-/*
-Initialize the Bytes per Sector variable value.
-
-@internalComponent
-@released
-*/
-void CFat32FileSystem::ComputeBytesPerSector()
-{
-	iBytesPerSector = iFAT32BootSector.BytesPerSector();
-}
-
-/*
-Sets the total number of clusters in iData segment of the FAT volume
-
-
-@internalComponent
-@released
-
-@aPartitionSize partition size in bytes
-*/
-void CFat32FileSystem::ComputeTotalClusters(Long64 aPartitionSize)
-{
-	unsigned int totalDataSectors = iFAT32BootSector.TotalSectors(aPartitionSize) - 
-									((iFAT32BootSector.NumberOfFats() * 
-									iFAT32BootSector.FatSectors32()) + 
-									iRootDirSectors+iFAT32BootSector.ReservedSectors());
-
- 	iTotalClusters = totalDataSectors / iFAT32BootSector.SectorsPerCluster();
-	if(iTotalClusters < KMinimumFat32Clusters)
-	{
-		throw ErrorHandler(BOOTSECTORERROR,"Low Partition Size",__FILE__, __LINE__);
-	}
-	else if(iTotalClusters > KMaximumFat32Clusters)
-	{
-		throw ErrorHandler(BOOTSECTORERROR,"high Partition Size",__FILE__, __LINE__);
-	}
-}
-/**
-This methods encapsulates the function call to write a complete FAT32 Image
-
-@internalComponent
-@released
-
-@param aPartitionSize partition size in bytes
-@param aNodeList Directory structure 
-@param aOutPutStream output stream for writing file image
-@param aImageFileName image file name 
-@param aLogFileName log file name 
-@param aConfigurableFatAttributes ConfigurableFatAttributes
-*/
-
-void CFat32FileSystem::Execute(Long64 aPartitionSize,EntryList aNodeList,
-							   ofstream& aOutPutStream,ConfigurableFatAttributes* aConfigurableFatAttributes)
-{
-	CDirRegion* dirRegionPtr = NULL;
-	try
-	{
-		CreateBootSector(aPartitionSize,aConfigurableFatAttributes);
-		ComputeTotalClusters(aPartitionSize);
-		WriteBootSector(aOutPutStream);
-		dirRegionPtr = new CDirRegion(aNodeList,this);
-		dirRegionPtr->Execute();
-		iClustersPerEntry = dirRegionPtr->GetClustersPerEntryMap();
-		CreateFSinfoSector(aOutPutStream);
-		RestReservedSectors(aOutPutStream);
-		CreateFatTable(aOutPutStream);
-		dirRegionPtr->WriteClustersIntoFile(aOutPutStream);
-		delete dirRegionPtr;
-		dirRegionPtr = NULL;
-	}
-	catch(ErrorHandler &aError)
-	{
-		delete dirRegionPtr;
-		dirRegionPtr = NULL;
-		throw ErrorHandler(aError.iMessageIndex,(char*)aError.iSubMessage.c_str(),(char*)aError.iFileName.c_str(),aError.iLineNumber);
-	}
-	/**
-	Irrespective of successful or unsuccessful data drive image generation ROFSBUILD
-	may try to generate images for successive ".oby" file input.
-	During this course unhandled exceptions may cause leaving some memory on heap 
-	unused. so the unhandled exceptions handling is used to free the memory allocated 
-	on heap. 
-	*/
-	catch(...)
-	{
-		delete dirRegionPtr;
-		dirRegionPtr = NULL;
-		throw ErrorHandler(UNKNOWNERROR, __FILE__, __LINE__);
-	}
-}
-
-/**
-Destructor of class CFat32FileSystem
-
-@internalComponent
-@released
-*/
-CFat32FileSystem::~CFat32FileSystem()
-{
-	delete[] FSinfoData;
-};
+/*
+* 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: 
+* CFat32FileSystem is the concrete class which is responsible for 
+* creating a FAT32 image. This class constitutes the method to 
+* create boot sector, FAT Table and data region of a FAT32 Image
+* @internalComponent
+* @released
+*
+*/
+
+#include"fat32filesystem.h"
+
+/**
+Initializes the boot sector of a FAT 32 volume
+
+@internalComponent
+@released
+
+@param aPartitionSize partition size in bytes
+@param aConfigurableFatAttributes ConfigurableFatAttributes
+*/
+void CFat32FileSystem::CreateBootSector(Long64 aPartitionSize,ConfigurableFatAttributes* aConfigurableFatAttributes)
+{
+	//initializes the boot sector values
+	iFAT32BootSector.SetOEMName();
+	unsigned char* OEMName =  iFAT32BootSector.OEMName();
+	iFAT32BootSector.SetJumpInstruction();
+	unsigned char* JmpBoot = iFAT32BootSector.JumpInstruction();
+	iFAT32BootSector.SetBytesPerSector(aConfigurableFatAttributes->iDriveSectorSize);
+	unsigned short BytesPerSector = (unsigned short)iFAT32BootSector.BytesPerSector();
+	iFAT32BootSector.ComputeSectorsPerCluster(aPartitionSize);
+	unsigned char SectorsPerCluster = iFAT32BootSector.SectorsPerCluster();
+	iFAT32BootSector.SetReservedSectors();
+	unsigned short ReservedSectors =  iFAT32BootSector.ReservedSectors();
+	iFAT32BootSector.SetNumberOfFats(aConfigurableFatAttributes->iDriveNoOfFATs);
+	unsigned char NumFats = iFAT32BootSector.NumberOfFats();
+	iFAT32BootSector.SetRootDirEntries();
+	unsigned short RootDirEntries = iFAT32BootSector.RootDirEntries();
+	iFAT32BootSector.ComputeTotalSectors(aPartitionSize);
+	unsigned short LowSectors = iFAT32BootSector.LowSectorsCount();
+	iFAT32BootSector.SetMedia();
+	unsigned char Media = iFAT32BootSector.Media();
+	iFAT32BootSector.ComputeFatSectors(aPartitionSize);
+	unsigned short FatSectors = iFAT32BootSector.FatSectors();
+	iFAT32BootSector.SetSectorsPerTrack();
+	unsigned short SectorPerTrack = iFAT32BootSector.SectorsPerTrack();
+	iFAT32BootSector.SetNumberOfHeads();
+	unsigned short NumberOfHeads = iFAT32BootSector.NumberOfHeads();
+	iFAT32BootSector.SetHiddenSectors();
+	unsigned int HiddenSectors = iFAT32BootSector.HiddenSectors();
+	unsigned int HighSectorsCount = iFAT32BootSector.HighSectorsCount();
+	unsigned int FatSectors32 = iFAT32BootSector.FatSectors32();
+	iFAT32BootSector.SetExtFlags();
+	unsigned short ExtFlags = iFAT32BootSector.ExtFlags();
+	iFAT32BootSector.SetFileSystemVersion();
+	unsigned short FileSystemVersion = iFAT32BootSector.FileSystemVersion();
+	iFAT32BootSector.SetRootCluster();
+	unsigned int RootCluster =  iFAT32BootSector.RootCluster();
+	iFAT32BootSector.SetFSInfo();
+	unsigned short FSInfo  = iFAT32BootSector.FSInfo();
+	iFAT32BootSector.SetBackUpBootSector();
+	unsigned short BackUpBootSector = iFAT32BootSector.BackUpBootSector();
+	iFAT32BootSector.SetFutureReserved();
+	unsigned char* FutureReserved = iFAT32BootSector.FutureReserved();
+	iFAT32BootSector.SetBootSectorDriveNumber();
+	unsigned char BootSectorDriveNumber = iFAT32BootSector.BootSectorDriveNumber();
+	iFAT32BootSector.SetReservedByte();
+	unsigned char ReservedByte = iFAT32BootSector.ReservedByte();
+	iFAT32BootSector.SetBootSignature();
+	unsigned char BootSignature = iFAT32BootSector.BootSignature();
+	iFAT32BootSector.SetVolumeId();
+	unsigned int VolumeId = iFAT32BootSector.VolumeId();
+	iFAT32BootSector.SetVolumeLab(aConfigurableFatAttributes->iDriveVolumeLabel);
+	unsigned char* VolumeLab = iFAT32BootSector.VolumeLab();
+	iFAT32BootSector.SetFileSysType();
+	unsigned char* FileSystemType = iFAT32BootSector.FileSysType();
+
+	//copying of boot sector values in to the array
+	iData = new unsigned char[BytesPerSector];
+	unsigned int pos = 0;
+	memcpy(&iData[pos],JmpBoot,3);
+	pos += 3;
+	memcpy(&iData[pos],OEMName,8);
+	pos += 8;
+	memcpy(&iData[pos],&BytesPerSector,2);
+	pos += 2;
+	memcpy(&iData[pos],&SectorsPerCluster,1);
+	pos += 1;
+	memcpy(&iData[pos],&ReservedSectors,2);
+	pos += 2;
+	memcpy(&iData[pos],&NumFats,1);
+	pos += 1;
+	memcpy(&iData[pos],&RootDirEntries,2);
+	pos += 2;
+	memcpy(&iData[pos],&LowSectors,2);
+	pos += 2;
+	memcpy(&iData[pos],&Media,1);
+	pos += 1;
+	memcpy(&iData[pos],&FatSectors,2);
+	pos += 2;
+	memcpy(&iData[pos],&SectorPerTrack,2);
+	pos += 2;
+	memcpy(&iData[pos],&NumberOfHeads,2);
+	pos += 2;
+	memcpy(&iData[pos],&HiddenSectors,4);
+	pos += 4;
+	memcpy(&iData[pos],&HighSectorsCount,4);
+	pos += 4;
+	memcpy(&iData[pos],&FatSectors32,4);
+	pos += 4;
+	memcpy(&iData[pos],&ExtFlags,2);
+	pos += 2;
+	memcpy(&iData[pos],&FileSystemVersion,2);
+	pos += 2;
+	memcpy(&iData[pos],&RootCluster,4);
+	pos += 4;
+	memcpy(&iData[pos],&FSInfo,2);
+	pos += 2;
+	memcpy(&iData[pos],&BackUpBootSector,2);
+	pos += 2;
+	memcpy(&iData[pos],FutureReserved,12);
+	pos += 12;
+	memcpy(&iData[pos],&BootSectorDriveNumber,1);
+	pos += 1;
+	memcpy(&iData[pos],&ReservedByte,1);
+	pos += 1;
+	memcpy(&iData[pos],&BootSignature,1);
+	pos += 1;
+	memcpy(&iData[pos],&VolumeId,4);
+	pos += 4;
+	memcpy(&iData[pos],VolumeLab,11);
+	pos += 11;
+	memcpy(&iData[pos],FileSystemType,8);
+	pos += 8;
+	while(pos < BytesPerSector)
+	{
+		iData[pos] = 0x00;
+		pos++;
+	}
+	// Set sector [510] as 0xAA and [511] as 0x55 to mark the end of boot sector
+	iData[KSizeOfFatBootSector-2] = 0x55;
+	iData[KSizeOfFatBootSector-1] = 0xAA;
+	// It is perfectly ok for the last two bytes of the boot sector to also 
+	// have the signature 0xAA55.
+	iData[BytesPerSector-2] = 0x55;
+	iData[BytesPerSector-1] = 0xAA;
+	ComputeClusterSizeInBytes();
+	ComputeRootDirSectors();
+	ComputeBytesPerSector();
+	MessageHandler::ReportMessage (INFORMATION,BOOTSECTORCREATEMSG, "FAT32");
+}
+
+/**
+Writes the boot sector of a FAT 32 volume
+
+@internalComponent
+@released
+
+@param aOutPutStream handle for the image file
+*/
+void CFat32FileSystem::WriteBootSector(ofstream& aOutPutStream)
+{
+	MessageHandler::ReportMessage (INFORMATION,BOOTSECTORWRITEMSG, "FAT32");
+	aOutPutStream.write(reinterpret_cast<char*>(&iData[0]),iFAT32BootSector.BytesPerSector());
+	aOutPutStream.flush();
+}
+
+/**
+Creates and writes the FAT Table sector of a FAT 32 volume
+
+@internalComponent
+@released
+
+@param aClustersPerEntryMap iDatastructure containing the mapping of clusters allocated to the file.
+@param aOutPutStream handle for the image file
+*/
+void CFat32FileSystem::CreateFatTable(ofstream& aOutPutStream)
+{
+	//data is written from cluster 2
+	unsigned int clusterCounter = 2;
+	unsigned int FATSizeInBytes = (iFAT32BootSector.FatSectors32()) * (iFAT32BootSector.BytesPerSector());
+	// Each FAT32 entries occupies 4 bytes, hence divided by 4
+	unsigned int totalFatEntries = FATSizeInBytes / 4;
+	//contains the address of FAT Table 	
+	unsigned int *FatTable = new unsigned int[totalFatEntries];
+
+	/**Say cluster 5 starts at 5 and occupies clusters 7 and 9. The FAT table should have the 
+	value 7 at	cluster location 5, the value 9 at cluster 7 and 'eof' value at cluster 9.
+	Below algorithm serves this algorithm
+	*/
+	int previousCluster;
+	FatTable[0] = KFat32FirstEntry;
+	FatTable[1] =  EOF32;
+	Iterator itr = iClustersPerEntry->begin();
+	while(itr !=  iClustersPerEntry->end())
+	{
+		previousCluster = itr->second;
+		if(iClustersPerEntry->count(itr->first) > 1)
+		{
+			for(unsigned int i = 1; i < iClustersPerEntry->count(itr->first); i++)
+			{
+				FatTable[previousCluster] = (++itr)->second;
+				previousCluster = itr->second;
+				++clusterCounter;
+			}
+		}
+		FatTable[previousCluster] = EOF32;
+		itr++;
+		++clusterCounter;
+	}
+	// Each FAT32 entries occupies 4 bytes, hence multiply by 4
+	string aFatString(reinterpret_cast<char*>(FatTable),clusterCounter*4);
+	delete[] FatTable;
+	if(clusterCounter < totalFatEntries)
+	{
+		// Each FAT32 entries occupies 4 bytes, hence multiply by 4
+		aFatString.append((totalFatEntries - clusterCounter)*4, 0);
+	}
+	MessageHandler::ReportMessage (INFORMATION,FATTABLEWRITEMSG,
+								   "FAT32");
+	//Write FAT table multiple times depending on the value of No of FATS set.
+	unsigned int noOfFats = iFAT32BootSector.NumberOfFats();
+	for(unsigned int i=0; i<noOfFats; i++)
+	{
+		aOutPutStream.write(aFatString.c_str(),aFatString.length());
+	}
+	aFatString.erase();
+	aOutPutStream.flush();
+}
+
+/**
+FSINfo iData structure specific to FAT32
+
+@internalComponent
+@released
+
+@param aOutPutStream handle for the image file
+*/
+void CFat32FileSystem::CreateFSinfoSector(ofstream& aOutPutStream)
+{
+	int counter = 0;
+	unsigned int bytesPerSector = iFAT32BootSector.BytesPerSector();
+	FSinfoData = new unsigned char[bytesPerSector];
+	iFSInfo.SetFSInfo();
+	memcpy(&FSinfoData[counter], &iFSInfo.FSI_LeadSign,4);
+	counter += 4;
+	memcpy(&FSinfoData[counter], &iFSInfo.FSI_Reserved,480);
+	counter += 480;
+	memcpy(&FSinfoData[counter], &iFSInfo.FSI_StrucSig,4);
+	counter += 4;
+	memcpy(&FSinfoData[counter], &iFSInfo.FSI_Free_Count,4);
+	counter += 4;
+	memcpy(&FSinfoData[counter], &iFSInfo.FSI_Nxt_Free,4);
+	counter += 4;
+	memcpy(&FSinfoData[counter], &iFSInfo.FSI_Reserved2,12);
+	counter += 12;
+	memcpy(&FSinfoData[counter], &iFSInfo.FSI_TrailSig,4);
+	counter += 4;
+	counter += (bytesPerSector-KSizeOfFatBootSector);
+	aOutPutStream.write(reinterpret_cast<char*>(&FSinfoData[0]),counter);
+	aOutPutStream.flush();	
+}
+
+/**
+ Initializes the left over reserved sectors of FAT32 image other than boot sector and FSinfo iData sector(sector 0 and 1)
+
+ @internalComponent
+ @released
+
+ @param aOutPutStream handle to file stream		
+*/
+void CFat32FileSystem::RestReservedSectors(ofstream& aOutPutStream)
+{
+	unsigned int bytesPerSector = iFAT32BootSector.BytesPerSector();
+	unsigned char* nullsector = new unsigned char[bytesPerSector];
+	for(unsigned int counter = 0; counter < bytesPerSector ; counter++)
+	{
+		nullsector[counter] = 0;
+	}
+	nullsector[KSizeOfFatBootSector-2] = 0x55;
+	nullsector[KSizeOfFatBootSector-1] = 0xAA;
+	for(unsigned int sectorcount = 2; sectorcount < (unsigned int)(iFAT32BootSector.ReservedSectors()) - 1; sectorcount++)
+	{
+		// Sector no 6 and 7 contains the duplicate copy of boot sector and FSInfo sector in a FAT32 Image
+		if(sectorcount == KBootBackupSector)
+		{
+			aOutPutStream.write(reinterpret_cast<char*>(&iData[0]),bytesPerSector);		
+			aOutPutStream.flush();
+		}
+		if(sectorcount == KFatBackupSector)
+		{
+			aOutPutStream.write(reinterpret_cast<char*>(&FSinfoData[0]),bytesPerSector);		
+			aOutPutStream.flush();
+		}
+		else
+		{
+			aOutPutStream.write(reinterpret_cast<char*>(&nullsector[0]),bytesPerSector);		
+			aOutPutStream.flush();
+		}
+	}
+	delete[] nullsector;
+	nullsector = NULL;
+}
+
+/**
+compute the cluster size in bytes,iClusterSize
+
+@internalComponent
+@released
+*/
+void CFat32FileSystem::ComputeClusterSizeInBytes()
+{
+	iClusterSize = iFAT32BootSector.SectorsPerCluster()*iFAT32BootSector.BytesPerSector();
+}
+
+/**
+Compute the count of sectors occupied by the root directory,iRootDirSectors.
+
+@internalComponent
+@released
+*/
+void CFat32FileSystem::ComputeRootDirSectors()
+{
+	iRootDirSectors = (iFAT32BootSector.RootDirEntries() * (KDefaultRootDirEntrySize) + 
+		              (iFAT32BootSector.BytesPerSector() - 1)) / iFAT32BootSector.BytesPerSector();
+}
+
+/*
+Initialize the Bytes per Sector variable value.
+
+@internalComponent
+@released
+*/
+void CFat32FileSystem::ComputeBytesPerSector()
+{
+	iBytesPerSector = iFAT32BootSector.BytesPerSector();
+}
+
+/*
+Sets the total number of clusters in iData segment of the FAT volume
+
+
+@internalComponent
+@released
+
+@aPartitionSize partition size in bytes
+*/
+void CFat32FileSystem::ComputeTotalClusters(Long64 aPartitionSize)
+{
+	unsigned int totalDataSectors = iFAT32BootSector.TotalSectors(aPartitionSize) - 
+									((iFAT32BootSector.NumberOfFats() * 
+									iFAT32BootSector.FatSectors32()) + 
+									iRootDirSectors+iFAT32BootSector.ReservedSectors());
+
+ 	iTotalClusters = totalDataSectors / iFAT32BootSector.SectorsPerCluster();
+	if(iTotalClusters < KMinimumFat32Clusters)
+	{
+		throw ErrorHandler(BOOTSECTORERROR,"Low Partition Size",__FILE__, __LINE__);
+	}
+	else if(iTotalClusters > KMaximumFat32Clusters)
+	{
+		throw ErrorHandler(BOOTSECTORERROR,"high Partition Size",__FILE__, __LINE__);
+	}
+}
+/**
+This methods encapsulates the function call to write a complete FAT32 Image
+
+@internalComponent
+@released
+
+@param aPartitionSize partition size in bytes
+@param aNodeList Directory structure 
+@param aOutPutStream output stream for writing file image
+@param aImageFileName image file name 
+@param aLogFileName log file name 
+@param aConfigurableFatAttributes ConfigurableFatAttributes
+*/
+
+void CFat32FileSystem::Execute(Long64 aPartitionSize,EntryList aNodeList,
+							   ofstream& aOutPutStream,ConfigurableFatAttributes* aConfigurableFatAttributes)
+{
+	CDirRegion* dirRegionPtr = NULL;
+	try
+	{
+		CreateBootSector(aPartitionSize,aConfigurableFatAttributes);
+		ComputeTotalClusters(aPartitionSize);
+		WriteBootSector(aOutPutStream);
+		dirRegionPtr = new CDirRegion(aNodeList,this);
+		dirRegionPtr->Execute();
+		iClustersPerEntry = dirRegionPtr->GetClustersPerEntryMap();
+		CreateFSinfoSector(aOutPutStream);
+		RestReservedSectors(aOutPutStream);
+		CreateFatTable(aOutPutStream);
+		dirRegionPtr->WriteClustersIntoFile(aOutPutStream);
+		delete dirRegionPtr;
+		dirRegionPtr = NULL;
+	}
+	catch(ErrorHandler &aError)
+	{
+		delete dirRegionPtr;
+		dirRegionPtr = NULL;
+		throw ErrorHandler(aError.iMessageIndex,(char*)aError.iSubMessage.c_str(),(char*)aError.iFileName.c_str(),aError.iLineNumber);
+	}
+	/**
+	Irrespective of successful or unsuccessful data drive image generation ROFSBUILD
+	may try to generate images for successive ".oby" file input.
+	During this course unhandled exceptions may cause leaving some memory on heap 
+	unused. so the unhandled exceptions handling is used to free the memory allocated 
+	on heap. 
+	*/
+	catch(...)
+	{
+		delete dirRegionPtr;
+		dirRegionPtr = NULL;
+		throw ErrorHandler(UNKNOWNERROR, __FILE__, __LINE__);
+	}
+}
+
+/**
+Destructor of class CFat32FileSystem
+
+@internalComponent
+@released
+*/
+CFat32FileSystem::~CFat32FileSystem()
+{
+	delete[] FSinfoData;
+};
--- a/imgtools/imglib/filesystem/source/fatbasebootsector.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/source/fatbasebootsector.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,596 +1,596 @@
-/*
-* 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 file contains the definition of class TFATBaseBootSector. 
-* TFATBaseBootSector is the base class for the boot sector class 
-* of different FAT file system type.This contains the data member 
-* representing the common fields in each FAT image type
-* @internalComponent
-* @released
-*
-*/
-
-#include "fatbasebootsector.h"
-
-/**
-Constructor of the base boot sector class
-
-@internalComponent
-@released
-*/
-TFATBaseBootSector::TFATBaseBootSector()
-{
-}
-
-/**
-Destructor of the base boot sector class
-
-@internalComponent
-@released
-*/
-TFATBaseBootSector::~TFATBaseBootSector()
-{
-}
-
-/**
-Function Sets the OEM name generally, Indication of what system 
-formats the volume
-
-@internalComponent
-@released
-*/
-void TFATBaseBootSector::SetOEMName()
-	{
-		strcpy( reinterpret_cast<char*>(iOEMName),KDefaultOEMName);
-	}
-
-/**
-Function to get the OEM name
-
-@internalComponent
-@released
-
-@return OEM Name
-*/
-unsigned char* TFATBaseBootSector::OEMName() 
-	{
-		return iOEMName;
-	}
-
-/**
-Function to set the jump instructions
-
-@internalComponent
-@released
-*/
-void TFATBaseBootSector::SetJumpInstruction()
-{
-	iJmpBoot[0]= 0xEB;
-	iJmpBoot[1]= 0x5A;
-	iJmpBoot[2]= 0x90;
-}
-
-/**
-Function to get the jump instructions
-
-@internalComponent
-@released
-
-@return jump boot instruction
-*/
-unsigned char* TFATBaseBootSector::JumpInstruction()  
-{
-	return iJmpBoot;
-}
-
-
-/**
-Function to set the bytes per sector.  
-
-@internalComponent
-@released
-
-@param aDriveSectorSize Sector size in bytes 
-*/
-void TFATBaseBootSector::SetBytesPerSector(unsigned int aDriveSectorSize)
-{
-	// Take the default value if SectorSize is not provided by the user. 
-	if (aDriveSectorSize != 0)
-	{
-		unsigned short int acceptableValues[] = {512,1024,2048,4096};
-		unsigned short int acceptableValuesCount = 4;
-		bool validSectorSize = false;
-		for (unsigned int count=0; count<acceptableValuesCount; count++)
-		{
-			if(aDriveSectorSize == acceptableValues[count])
-			{
-				validSectorSize = true;
-				break;
-			}
-		}
-		// If invalid value for Sector Size is provided, consider the default value.
-		if (validSectorSize)
-		{
-			iBytesPerSector=aDriveSectorSize;
-			return;
-		}
-		else
-		{
-			std::cout<<"Warning: Invalid Sector Size value. Default value is considered.\n";
-		}
-	}
-	iBytesPerSector=KDefaultBytesPerSector;	
-}
-
-/**
-Return the bytes per sector
-
-@internalComponent
-@released
-
-@return bytes per sector, hard coded as 512 here.
-*/
-unsigned int TFATBaseBootSector::BytesPerSector() const
-{
-	return iBytesPerSector;
-}
-
-/**
-Sets the number of Fats on the volume
-
-@internalComponent
-@released
-
-@param aDriveNoOfFATs Number of fats
-*/
-void TFATBaseBootSector::SetNumberOfFats(unsigned int aDriveNoOfFATs) 
-{
-	// Take the default value if No of FATs is not provided by the user. 
-	if (aDriveNoOfFATs != 0)
-	{
-		// If invalid value for No of FATs is provided, generate a warning and take the default value. 
-		if ((aDriveNoOfFATs>255) || (aDriveNoOfFATs<1))
-		{
-			std::cout<<"Warning: No of FATs should be between 0 and 256. Default value is considered.\n";
-			iNumberOfFats= KDefaultNumFats;
-			return;
-		}
-		iNumberOfFats= aDriveNoOfFATs;
-	}
-	else
-	{
-		iNumberOfFats= KDefaultNumFats;
-	}
-}
-
-
-/**
-Total sectors on the volume,This count includes the total count of all sectors 
-in all four regions of the volume.iTatalSectors is a 16 bit field and iTotalSectors32
-is a 32 bit field.Hence if the total sectors are more than 2^16(0x10000 in hex) 
-then iTotalSectors32 is set otherwise it is zero.
-
-@internalComponent
-@released
-
-@param aPartitionSize Partition size in bytes
-*/
-void TFATBaseBootSector::ComputeTotalSectors(Long64 aPartitionSize)
-{
-	int Log2OfBytesPerSector = Log2(iBytesPerSector);
-	unsigned long TotalSectors64 = (unsigned long)(aPartitionSize >> Log2OfBytesPerSector);
-	if(TotalSectors64 >= 0x10000)
-	{
-			iTotalSectors = 0;
-			iTotalSectors32 = (unsigned int) TotalSectors64;
-	}
-	else
-	{
-			iTotalSectors = (unsigned short)TotalSectors64;
-			iTotalSectors32=0;
-	}
-}
-
-/**
-Set the media descriptor,0xF8 is the standard for fixed (non removable) media.
-
-@internalComponent
-@released
-*/
-void TFATBaseBootSector::SetMedia()
-{
-	iMedia=KBPBMedia;
-}
-
-/**
-This methods gets the media descriptor
-
-@internalComponent
-@released
-
-@return media descriptor
-*/
-unsigned char TFATBaseBootSector::Media() const
-{
-	return iMedia;
-}
-
-/**
-Set the number of hidden sectors in the volume,Count of hidden sector
-preceding the partition.
-
-@internalComponent
-@released
-*/
-void TFATBaseBootSector::SetHiddenSectors()
-{
-	iHiddenSectors=KDefaultHiddenSectors;
-}
-
-/**
-Gets the number of hidden sectors in the volume
-
-@internalComponent
-@released
-
-@return the number of hidden sectors in a given FAT Volume
-*/
-unsigned int TFATBaseBootSector::HiddenSectors() const
-{
-	return iHiddenSectors;
-}
-
-/**
-Set the sectors per track preceding the partition.
-
-@internalComponent
-@released
-*/
-void TFATBaseBootSector::SetSectorsPerTrack()
-{
-	iSectorsPerTrack=KDefaultSectorsPerTrack;// default value for flash memory
-}
-
-/**
-Gets the number sectors per track in the volume
-
-@internalComponent
-@released
-
-@return the number of sectors per track in a given FAT Volume
-*/
-unsigned short TFATBaseBootSector::SectorsPerTrack() const
-{
-	 return iSectorsPerTrack;
-}
-
-/**
-Set the number of heads
-
-@internalComponent
-@released
-*/
-void TFATBaseBootSector::SetNumberOfHeads()
-{
-	iNumHeads=KDefaultNumHeads;// default value for flash memory
-}
-
-/**
-Gets the the number of heads
-
-@internalComponent
-@released
-
-@return number of heads in a given FAT Volume
-*/
-unsigned short TFATBaseBootSector::NumberOfHeads() const
-{
-	return iNumHeads;// default value for flash memory
-}
-
-/**
-Set the Physical drive number,not used in Symbian OS
-
-@internalComponent
-@released
-*/
-void TFATBaseBootSector::SetBootSectorDriveNumber()
-{
-	iPhysicalDriveNumber=KDefaultDriveNumber;
-}
-
-/**
-Function to return drive number
-
-@internalComponent
-@released
-
-@return Physical drive number, not used in Symbian OS
-*/
-unsigned char TFATBaseBootSector::BootSectorDriveNumber() const
-{
-	return iPhysicalDriveNumber;
-}
-
-/**
-Set the reserved byte value
-
-@internalComponent
-@released
-*/
-void TFATBaseBootSector::SetReservedByte()
-{
-	iReservedByte=KDefaultReservedByte;
-}
-
-/**
-Get the value of reserved byte in boot sector
-
-@internalComponent
-@released
-
-@return Returns the reserved byte value
-*/
-unsigned char TFATBaseBootSector::ReservedByte() const
-{
-	return iReservedByte;
-}
-
-/**
-Set the extended boot signature
-
-@internalComponent
-@released
-
-*/
-void TFATBaseBootSector::SetBootSignature() 
-{
-	iBootSign=KDefaultBootSignature;
-}
-
-/**
-Gets the extended boot signature
-
-@internalComponent
-@released
-
-@return boot signature
-*/
-unsigned char TFATBaseBootSector::BootSignature() const
-{
-	return iBootSign;
-}
-
-/**
-Set the unique volume serial number,This ID is usually generated by 
-simply combining the current date and time in to 32 bit value.
-
-@internalComponent
-@released
-*/
-void TFATBaseBootSector::SetVolumeId()
-{	
-	time_t rawtime;
-	time(&rawtime);
-	iVolumeId=rawtime;
-}
-
-/**
-Returns the volume id 
-
-@internalComponent
-@released
-
-@return volume id field of the boot sector 
-*/
-unsigned int TFATBaseBootSector::VolumeId() const
-{
-return iVolumeId ;
-}
-
-/**
-Set the volume's label
-
-@internalComponent
-@released
-
-@param aVolumeLable Data Drive Volume Label
-*/
-void TFATBaseBootSector::SetVolumeLab(String aVolumeLable)
-{
-	// Set the default value of VolumeLable(i.e. "NO NAME    ") if not provided
-	// by the user.
-	if (aVolumeLable.empty())	
-	{
-		strcpy(reinterpret_cast<char*>(iVolumeLabel),KDefaultVolumeLabel);
-	}
-	else 
-	{
-		// If the volume label provided is greater than 11 characters then consider only 
-		// the first 11 characters and generate a warning.
-		int volumeMaxLangth= 11;
-		int volumeLabelSize= aVolumeLable.size();
-		if (volumeLabelSize > volumeMaxLangth)
-		{
-			std::cout<<"Warning: Size overflow for Data Drive Volume Label. Truncating to 11-bytes.\n";	
-			aVolumeLable.resize(volumeMaxLangth);
-			strcpy(reinterpret_cast<char*>(iVolumeLabel),aVolumeLable.c_str());
-			return;
-		}
-		
-		// If the VolumeLable provided is less than 11-characters then pad the 
-		// remaining bytes with white-spaces.		
-		if (volumeLabelSize < KMaxVolumeLabel)
-		{
-			while(volumeLabelSize < 11)
-			{
-				aVolumeLable.append(" ");
-				volumeLabelSize = aVolumeLable.size();
-			}	
-		}
-		strcpy(reinterpret_cast<char*>(iVolumeLabel),aVolumeLable.c_str());
-	}
-}
-
-/**
-returns  the volume's label
-
-@internalComponent
-@released
-
-*/
-unsigned char* TFATBaseBootSector::VolumeLab() 
-{
-	return iVolumeLabel;
-}
-
-/**
-Returns the number of reserved sectors on the volume
-
-@internalComponent
-@released
-
-@return iReservedSectors
-*/
-unsigned short TFATBaseBootSector::ReservedSectors() const
-{
-	return iReservedSectors;
-}
-
-/**
-Returns the number of Fats on the volume
-
-@internalComponent
-@released
-
-@return iNumberOfFats
-*/
-unsigned char TFATBaseBootSector::NumberOfFats() const
-{
-	return iNumberOfFats;
-}
-
-/**
-Returns the number of entries allowed in the root directory, specific to Fat12/16, zero for FAT32
-
-@internalComponent
-@released
-
-@return iRootDirEntries
-*/
-unsigned short TFATBaseBootSector::RootDirEntries() const
-{
-	return iRootDirEntries;
-}
-
-/**
-Returns the total sectors on the volume, 
-
-@internalComponent
-@released
-
-@return iTotalSectors 
-*/
-unsigned int TFATBaseBootSector::TotalSectors(Long64 aPartitionSize) const
-{
-	if((aPartitionSize/iBytesPerSector)>= 0x10000)	
-	return iTotalSectors32;
-	else 
-	return iTotalSectors;
-}
-
-/**
-Returns base 2 Logarithm of a number 
-
-@internalComponent
-@released
-
-@param aNum number whose logarithm is to be taken
-@return log base 2 of the number passed
-*/
-int TFATBaseBootSector::Log2(int aNum) 
-{
-	int res=-1;
-	while(aNum)
-		{
-		res++;
-		aNum>>=1;
-		}
-	return(res);
-}
-
-/**
-Returns the sectors per cluster ratio
-
-@internalComponent
-@released
-
-@return iSectorsPerCluster
-*/
-unsigned char TFATBaseBootSector::SectorsPerCluster() const
-{
-	return iSectorsPerCluster;
-}
-
-/**
-Returns the 16 bit count of total sectors on the volume 
-
-@internalComponent
-@released
-
-@return iTotalSectors 
-*/
-unsigned short TFATBaseBootSector::LowSectorsCount() const
-{
-	return iTotalSectors;
-}
-
-/**
-Returns the 32 bit count of total sectors on the volume 
-
-@internalComponent
-@released
-
-@return iTotalSectors 
-*/
-unsigned int TFATBaseBootSector::HighSectorsCount() const
-{
-	return iTotalSectors32;
-}
-
-/**
-Returns sectors used for the Fat table, zero for FAT32
-
-@internalComponent
-@released
-
-@return iFatSectors
-*/
-unsigned short TFATBaseBootSector::FatSectors() const
-{
-	return (unsigned short)iFatSectors;
-}
-
-/**
-Returns sectors used for the Fat table in FAT32
-
-@internalComponent
-@released
-
-@return iFatSectors32
-*/
-unsigned int TFATBaseBootSector::FatSectors32() const
-{
-	return iFatSectors32;
-}
+/*
+* 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 file contains the definition of class TFATBaseBootSector. 
+* TFATBaseBootSector is the base class for the boot sector class 
+* of different FAT file system type.This contains the data member 
+* representing the common fields in each FAT image type
+* @internalComponent
+* @released
+*
+*/
+
+#include "fatbasebootsector.h"
+
+/**
+Constructor of the base boot sector class
+
+@internalComponent
+@released
+*/
+TFATBaseBootSector::TFATBaseBootSector()
+{
+}
+
+/**
+Destructor of the base boot sector class
+
+@internalComponent
+@released
+*/
+TFATBaseBootSector::~TFATBaseBootSector()
+{
+}
+
+/**
+Function Sets the OEM name generally, Indication of what system 
+formats the volume
+
+@internalComponent
+@released
+*/
+void TFATBaseBootSector::SetOEMName()
+	{
+		strcpy( reinterpret_cast<char*>(iOEMName),KDefaultOEMName);
+	}
+
+/**
+Function to get the OEM name
+
+@internalComponent
+@released
+
+@return OEM Name
+*/
+unsigned char* TFATBaseBootSector::OEMName() 
+	{
+		return iOEMName;
+	}
+
+/**
+Function to set the jump instructions
+
+@internalComponent
+@released
+*/
+void TFATBaseBootSector::SetJumpInstruction()
+{
+	iJmpBoot[0]= 0xEB;
+	iJmpBoot[1]= 0x5A;
+	iJmpBoot[2]= 0x90;
+}
+
+/**
+Function to get the jump instructions
+
+@internalComponent
+@released
+
+@return jump boot instruction
+*/
+unsigned char* TFATBaseBootSector::JumpInstruction()  
+{
+	return iJmpBoot;
+}
+
+
+/**
+Function to set the bytes per sector.  
+
+@internalComponent
+@released
+
+@param aDriveSectorSize Sector size in bytes 
+*/
+void TFATBaseBootSector::SetBytesPerSector(unsigned int aDriveSectorSize)
+{
+	// Take the default value if SectorSize is not provided by the user. 
+	if (aDriveSectorSize != 0)
+	{
+		unsigned short int acceptableValues[] = {512,1024,2048,4096};
+		unsigned short int acceptableValuesCount = 4;
+		bool validSectorSize = false;
+		for (unsigned int count=0; count<acceptableValuesCount; count++)
+		{
+			if(aDriveSectorSize == acceptableValues[count])
+			{
+				validSectorSize = true;
+				break;
+			}
+		}
+		// If invalid value for Sector Size is provided, consider the default value.
+		if (validSectorSize)
+		{
+			iBytesPerSector=aDriveSectorSize;
+			return;
+		}
+		else
+		{
+			cout<<"Warning: Invalid Sector Size value. Default value is considered.\n";
+		}
+	}
+	iBytesPerSector=KDefaultBytesPerSector;	
+}
+
+/**
+Return the bytes per sector
+
+@internalComponent
+@released
+
+@return bytes per sector, hard coded as 512 here.
+*/
+unsigned int TFATBaseBootSector::BytesPerSector() const
+{
+	return iBytesPerSector;
+}
+
+/**
+Sets the number of Fats on the volume
+
+@internalComponent
+@released
+
+@param aDriveNoOfFATs Number of fats
+*/
+void TFATBaseBootSector::SetNumberOfFats(unsigned int aDriveNoOfFATs) 
+{
+	// Take the default value if No of FATs is not provided by the user. 
+	if (aDriveNoOfFATs != 0)
+	{
+		// If invalid value for No of FATs is provided, generate a warning and take the default value. 
+		if ((aDriveNoOfFATs>255) || (aDriveNoOfFATs<1))
+		{
+			cout<<"Warning: No of FATs should be between 0 and 256. Default value is considered.\n";
+			iNumberOfFats= KDefaultNumFats;
+			return;
+		}
+		iNumberOfFats= aDriveNoOfFATs;
+	}
+	else
+	{
+		iNumberOfFats= KDefaultNumFats;
+	}
+}
+
+
+/**
+Total sectors on the volume,This count includes the total count of all sectors 
+in all four regions of the volume.iTatalSectors is a 16 bit field and iTotalSectors32
+is a 32 bit field.Hence if the total sectors are more than 2^16(0x10000 in hex) 
+then iTotalSectors32 is set otherwise it is zero.
+
+@internalComponent
+@released
+
+@param aPartitionSize Partition size in bytes
+*/
+void TFATBaseBootSector::ComputeTotalSectors(Long64 aPartitionSize)
+{
+	int Log2OfBytesPerSector = Log2(iBytesPerSector);
+	unsigned long TotalSectors64 = (unsigned long)(aPartitionSize >> Log2OfBytesPerSector);
+	if(TotalSectors64 >= 0x10000)
+	{
+			iTotalSectors = 0;
+			iTotalSectors32 = (unsigned int) TotalSectors64;
+	}
+	else
+	{
+			iTotalSectors = (unsigned short)TotalSectors64;
+			iTotalSectors32=0;
+	}
+}
+
+/**
+Set the media descriptor,0xF8 is the standard for fixed (non removable) media.
+
+@internalComponent
+@released
+*/
+void TFATBaseBootSector::SetMedia()
+{
+	iMedia=KBPBMedia;
+}
+
+/**
+This methods gets the media descriptor
+
+@internalComponent
+@released
+
+@return media descriptor
+*/
+unsigned char TFATBaseBootSector::Media() const
+{
+	return iMedia;
+}
+
+/**
+Set the number of hidden sectors in the volume,Count of hidden sector
+preceding the partition.
+
+@internalComponent
+@released
+*/
+void TFATBaseBootSector::SetHiddenSectors()
+{
+	iHiddenSectors=KDefaultHiddenSectors;
+}
+
+/**
+Gets the number of hidden sectors in the volume
+
+@internalComponent
+@released
+
+@return the number of hidden sectors in a given FAT Volume
+*/
+unsigned int TFATBaseBootSector::HiddenSectors() const
+{
+	return iHiddenSectors;
+}
+
+/**
+Set the sectors per track preceding the partition.
+
+@internalComponent
+@released
+*/
+void TFATBaseBootSector::SetSectorsPerTrack()
+{
+	iSectorsPerTrack=KDefaultSectorsPerTrack;// default value for flash memory
+}
+
+/**
+Gets the number sectors per track in the volume
+
+@internalComponent
+@released
+
+@return the number of sectors per track in a given FAT Volume
+*/
+unsigned short TFATBaseBootSector::SectorsPerTrack() const
+{
+	 return iSectorsPerTrack;
+}
+
+/**
+Set the number of heads
+
+@internalComponent
+@released
+*/
+void TFATBaseBootSector::SetNumberOfHeads()
+{
+	iNumHeads=KDefaultNumHeads;// default value for flash memory
+}
+
+/**
+Gets the the number of heads
+
+@internalComponent
+@released
+
+@return number of heads in a given FAT Volume
+*/
+unsigned short TFATBaseBootSector::NumberOfHeads() const
+{
+	return iNumHeads;// default value for flash memory
+}
+
+/**
+Set the Physical drive number,not used in Symbian OS
+
+@internalComponent
+@released
+*/
+void TFATBaseBootSector::SetBootSectorDriveNumber()
+{
+	iPhysicalDriveNumber=KDefaultDriveNumber;
+}
+
+/**
+Function to return drive number
+
+@internalComponent
+@released
+
+@return Physical drive number, not used in Symbian OS
+*/
+unsigned char TFATBaseBootSector::BootSectorDriveNumber() const
+{
+	return iPhysicalDriveNumber;
+}
+
+/**
+Set the reserved byte value
+
+@internalComponent
+@released
+*/
+void TFATBaseBootSector::SetReservedByte()
+{
+	iReservedByte=KDefaultReservedByte;
+}
+
+/**
+Get the value of reserved byte in boot sector
+
+@internalComponent
+@released
+
+@return Returns the reserved byte value
+*/
+unsigned char TFATBaseBootSector::ReservedByte() const
+{
+	return iReservedByte;
+}
+
+/**
+Set the extended boot signature
+
+@internalComponent
+@released
+
+*/
+void TFATBaseBootSector::SetBootSignature() 
+{
+	iBootSign=KDefaultBootSignature;
+}
+
+/**
+Gets the extended boot signature
+
+@internalComponent
+@released
+
+@return boot signature
+*/
+unsigned char TFATBaseBootSector::BootSignature() const
+{
+	return iBootSign;
+}
+
+/**
+Set the unique volume serial number,This ID is usually generated by 
+simply combining the current date and time in to 32 bit value.
+
+@internalComponent
+@released
+*/
+void TFATBaseBootSector::SetVolumeId()
+{	
+	time_t rawtime;
+	time(&rawtime);
+	iVolumeId=rawtime;
+}
+
+/**
+Returns the volume id 
+
+@internalComponent
+@released
+
+@return volume id field of the boot sector 
+*/
+unsigned int TFATBaseBootSector::VolumeId() const
+{
+return iVolumeId ;
+}
+
+/**
+Set the volume's label
+
+@internalComponent
+@released
+
+@param aVolumeLable Data Drive Volume Label
+*/
+void TFATBaseBootSector::SetVolumeLab(string aVolumeLable)
+{
+	// Set the default value of VolumeLable(i.e. "NO NAME    ") if not provided
+	// by the user.
+	if (aVolumeLable.empty())	
+	{
+		strcpy(reinterpret_cast<char*>(iVolumeLabel),KDefaultVolumeLabel);
+	}
+	else 
+	{
+		// If the volume label provided is greater than 11 characters then consider only 
+		// the first 11 characters and generate a warning.
+		int volumeMaxLangth= 11;
+		int volumeLabelSize= aVolumeLable.size();
+		if (volumeLabelSize > volumeMaxLangth)
+		{
+			cout<<"Warning: Size overflow for Data Drive Volume Label. Truncating to 11-bytes.\n";	
+			aVolumeLable.resize(volumeMaxLangth);
+			strcpy(reinterpret_cast<char*>(iVolumeLabel),aVolumeLable.c_str());
+			return;
+		}
+		
+		// If the VolumeLable provided is less than 11-characters then pad the 
+		// remaining bytes with white-spaces.		
+		if (volumeLabelSize < KMaxVolumeLabel)
+		{
+			while(volumeLabelSize < 11)
+			{
+				aVolumeLable.append(" ");
+				volumeLabelSize = aVolumeLable.size();
+			}	
+		}
+		strcpy(reinterpret_cast<char*>(iVolumeLabel),aVolumeLable.c_str());
+	}
+}
+
+/**
+returns  the volume's label
+
+@internalComponent
+@released
+
+*/
+unsigned char* TFATBaseBootSector::VolumeLab() 
+{
+	return iVolumeLabel;
+}
+
+/**
+Returns the number of reserved sectors on the volume
+
+@internalComponent
+@released
+
+@return iReservedSectors
+*/
+unsigned short TFATBaseBootSector::ReservedSectors() const
+{
+	return iReservedSectors;
+}
+
+/**
+Returns the number of Fats on the volume
+
+@internalComponent
+@released
+
+@return iNumberOfFats
+*/
+unsigned char TFATBaseBootSector::NumberOfFats() const
+{
+	return iNumberOfFats;
+}
+
+/**
+Returns the number of entries allowed in the root directory, specific to Fat12/16, zero for FAT32
+
+@internalComponent
+@released
+
+@return iRootDirEntries
+*/
+unsigned short TFATBaseBootSector::RootDirEntries() const
+{
+	return iRootDirEntries;
+}
+
+/**
+Returns the total sectors on the volume, 
+
+@internalComponent
+@released
+
+@return iTotalSectors 
+*/
+unsigned int TFATBaseBootSector::TotalSectors(Long64 aPartitionSize) const
+{
+	if((aPartitionSize/iBytesPerSector)>= 0x10000)	
+	return iTotalSectors32;
+	else 
+	return iTotalSectors;
+}
+
+/**
+Returns base 2 Logarithm of a number 
+
+@internalComponent
+@released
+
+@param aNum number whose logarithm is to be taken
+@return log base 2 of the number passed
+*/
+int TFATBaseBootSector::Log2(int aNum) 
+{
+	int res=-1;
+	while(aNum)
+		{
+		res++;
+		aNum>>=1;
+		}
+	return(res);
+}
+
+/**
+Returns the sectors per cluster ratio
+
+@internalComponent
+@released
+
+@return iSectorsPerCluster
+*/
+unsigned char TFATBaseBootSector::SectorsPerCluster() const
+{
+	return iSectorsPerCluster;
+}
+
+/**
+Returns the 16 bit count of total sectors on the volume 
+
+@internalComponent
+@released
+
+@return iTotalSectors 
+*/
+unsigned short TFATBaseBootSector::LowSectorsCount() const
+{
+	return iTotalSectors;
+}
+
+/**
+Returns the 32 bit count of total sectors on the volume 
+
+@internalComponent
+@released
+
+@return iTotalSectors 
+*/
+unsigned int TFATBaseBootSector::HighSectorsCount() const
+{
+	return iTotalSectors32;
+}
+
+/**
+Returns sectors used for the Fat table, zero for FAT32
+
+@internalComponent
+@released
+
+@return iFatSectors
+*/
+unsigned short TFATBaseBootSector::FatSectors() const
+{
+	return (unsigned short)iFatSectors;
+}
+
+/**
+Returns sectors used for the Fat table in FAT32
+
+@internalComponent
+@released
+
+@return iFatSectors32
+*/
+unsigned int TFATBaseBootSector::FatSectors32() const
+{
+	return iFatSectors32;
+}
--- a/imgtools/imglib/filesystem/source/filesysteminterface.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/source/filesysteminterface.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,125 +1,125 @@
-/*
-* 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 class provides the interface to external tools which can
-* use FileSystem component library. Upon external request this class 
-* classifies the request type either FAT16 or FAT32 and invokes 
-* the specific functions to generate the FAT image.
-* @internalComponent
-* @released
-*
-*/
-
-#include"errorhandler.h"
-#include"filesysteminterface.h"
-#include"fat16filesystem.h"
-#include"fat32filesystem.h"
-#include"dirregion.h"
-
-
-//static member definition
-
-Ofstream CFileSystemInterFace::iOutputStream;
-
-/**
-API exposed by the  FileSystem component to be used by an external component(s).
-This is method to be used by the external component for passing information required 
-by the FileSystem component
-
-@internalComponent
-@released
-
-@param aNodeList Directory structure 
-@param aFileSystem file system type
-@param aImageFileName image file name 
-@param aLogFileName log file name 
-@param aPartitionSize partition size in bytes
-*/
-FILESYSTEM_API int CFileSystemInterFace::CreateFilesystem(EntryList* aNodeList , 
-										   TFileSystem aFileSystem,
-										   char* aImageFileName, 
-										   char* aLogFileName,
-										   ConfigurableFatAttributes* aConfigurableFatAttributes,
-										   Long64 aPartitionSize)
-{
-	
-	
-	CFileSystem* iFileSystem = NULL;
-	try
-	{
-		MessageHandler::StartLogging (aLogFileName);
-		iOutputStream.open(aImageFileName,ios::out|ios::binary);
-		if(iOutputStream.fail() == true )
-		{
-			throw ErrorHandler(FILEOPENERROR,aImageFileName,__FILE__, __LINE__);
-		}
-		switch(aFileSystem)
-		{
-			case EFAT16:
-				iFileSystem = new CFat16FileSystem;
-				break;
-			
-			case EFAT32:
-				iFileSystem= new CFat32FileSystem;
-				break;
-			default:
-				return EFSNotSupported;
-				break;
-
-		}
-		iFileSystem->Execute(aPartitionSize,*aNodeList,iOutputStream,aConfigurableFatAttributes);
-		delete iFileSystem;
-		iFileSystem = NULL;
-		iOutputStream.close();
-		MessageHandler::CleanUp();
-	}
-	catch(ErrorHandler &error)
-	{
-		iOutputStream.close();
-		delete iFileSystem;
-		iFileSystem = NULL;
-		MessageHandler::StartLogging (aLogFileName);
-		error.Report();
-		MessageHandler::CleanUp();
-		return EFileSystemError;
-	}
-	/**
-	Irrespective of successful or unsuccessful data drive image generation ROFSBUILD
-	may try to generate images for successive oby file input.
-	During this course unhandled exceptions may cause leaving some memory on heap 
-	unused. so the unhandled exceptions handling is used to free the memory allocated 
-	on heap. 
-	*/
-	catch(...)
-	{
-		iOutputStream.close();
-		delete iFileSystem;
-		iFileSystem = NULL;
-		return EFileSystemError;
-	}
-	return 0;
-}
-
-
-/**
-Constructor of Class ConfigurableFatAttributes
-
-@internalComponent
-@released
-*/
-ConfigurableFatAttributes::ConfigurableFatAttributes()
-{
-	iDriveSectorSize = 0;
-	iDriveNoOfFATs = 0;
-}
+/*
+* 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 class provides the interface to external tools which can
+* use FileSystem component library. Upon external request this class 
+* classifies the request type either FAT16 or FAT32 and invokes 
+* the specific functions to generate the FAT image.
+* @internalComponent
+* @released
+*
+*/
+
+#include"errorhandler.h"
+#include"filesysteminterface.h"
+#include"fat16filesystem.h"
+#include"fat32filesystem.h"
+#include"dirregion.h"
+
+
+//static member definition
+
+Ofstream CFileSystemInterFace::iOutputStream;
+
+/**
+API exposed by the  FileSystem component to be used by an external component(s).
+This is method to be used by the external component for passing information required 
+by the FileSystem component
+
+@internalComponent
+@released
+
+@param aNodeList Directory structure 
+@param aFileSystem file system type
+@param aImageFileName image file name 
+@param aLogFileName log file name 
+@param aPartitionSize partition size in bytes
+*/
+FILESYSTEM_API int CFileSystemInterFace::CreateFilesystem(EntryList* aNodeList , 
+										   TFileSystem aFileSystem,
+										   char* aImageFileName, 
+										   char* aLogFileName,
+										   ConfigurableFatAttributes* aConfigurableFatAttributes,
+										   Long64 aPartitionSize)
+{
+	
+	
+	CFileSystem* iFileSystem = NULL;
+	try
+	{
+		MessageHandler::StartLogging (aLogFileName);
+		iOutputStream.open(aImageFileName,ios_base::out|ios_base::binary);
+		if(iOutputStream.fail() == true )
+		{
+			throw ErrorHandler(FILEOPENERROR,aImageFileName,__FILE__, __LINE__);
+		}
+		switch(aFileSystem)
+		{
+			case EFAT16:
+				iFileSystem = new CFat16FileSystem;
+				break;
+			
+			case EFAT32:
+				iFileSystem= new CFat32FileSystem;
+				break;
+			default:
+				return EFSNotSupported;
+				break;
+
+		}
+		iFileSystem->Execute(aPartitionSize,*aNodeList,iOutputStream,aConfigurableFatAttributes);
+		delete iFileSystem;
+		iFileSystem = NULL;
+		iOutputStream.close();
+		MessageHandler::CleanUp();
+	}
+	catch(ErrorHandler &error)
+	{
+		iOutputStream.close();
+		delete iFileSystem;
+		iFileSystem = NULL;
+		MessageHandler::StartLogging (aLogFileName);
+		error.Report();
+		MessageHandler::CleanUp();
+		return EFileSystemError;
+	}
+	/**
+	Irrespective of successful or unsuccessful data drive image generation ROFSBUILD
+	may try to generate images for successive oby file input.
+	During this course unhandled exceptions may cause leaving some memory on heap 
+	unused. so the unhandled exceptions handling is used to free the memory allocated 
+	on heap. 
+	*/
+	catch(...)
+	{
+		iOutputStream.close();
+		delete iFileSystem;
+		iFileSystem = NULL;
+		return EFileSystemError;
+	}
+	return 0;
+}
+
+
+/**
+Constructor of Class ConfigurableFatAttributes
+
+@internalComponent
+@released
+*/
+ConfigurableFatAttributes::ConfigurableFatAttributes()
+{
+	iDriveSectorSize = 0;
+	iDriveNoOfFATs = 0;
+}
--- a/imgtools/imglib/filesystem/source/longentry.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/source/longentry.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,209 +1,209 @@
-/*
-* 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 class provides the basic set and get operations associated 
-* with longentry attributes.
-* @internalComponent
-* @released
-*
-*/
-
-
-#include "longentry.h"
-
-/**
-Constructor responsible to initialze the possible attributes of 
-long entry
-
-@internalComponent
-@released
-
-@param aChckSum - Short entry checksum value
-*/
-
-CLongEntry::CLongEntry(	char aChckSum):
-						iDirOrder(0),
-						iAttribute(EAttrLongName),
-						iDirType(KDirSubComponent),
-						iCheckSum(aChckSum),
-						iFirstClusterNumberLow(0)						
-{
-}
-
-/**
-Destructor:
-
-@internalComponent
-@released
-
-*/
-CLongEntry::~CLongEntry()
-{
-}
-
-/**
-Function responsible to return Directory entry Order
-
-@internalComponent
-@released
-
-@return iDirOrder - Long name sub entry order
-*/
-char CLongEntry::GetDirOrder() const
-{
-	return iDirOrder;
-}
-
-/**
-Function responsible to initialize Directory entry Order
-
-@internalComponent
-@released
-
-@param aDirOrder - Long name sub entry order
-*/
-void CLongEntry::SetDirOrder(char aDirOrder)
-{
-	iDirOrder = aDirOrder;
-}
-
-/**
-Function responsible to return SubName1
-
-@internalComponent
-@released
-
-@return iSubName1 - returns sub name 1 of a long entry
-*/
-String& CLongEntry::GetSubName1()
-{
-	return iSubName1;
-}
-
-/**
-Function responsible to set SubName3
-
-@internalComponent
-@released
-
-@param aSubName1 - a long entry sub name 1
-*/
-void CLongEntry::SetSubName1(String aSubName1)
-{
-	iSubName1 = aSubName1;
-}
-
-/**
-Function responsible to return SubName2
-
-@internalComponent
-@released
-
-@return iSubName2 - returns sub name 2 of a long entry
-*/
-String& CLongEntry::GetSubName2()
-{
-	return iSubName2;
-}
-
-/**
-Function responsible to set SubName2
-
-@internalComponent
-@released
-
-@param aSubName2 - a long entry sub name 2
-*/
-void CLongEntry::SetSubName2(String aSubName2)
-{
-	iSubName2 = aSubName2;
-}
-
-/**
-Function responsible to return SubName3
-
-@internalComponent
-@released
-
-@return iSubName3 - returns sub name 3 of a long entry
-*/
-String& CLongEntry::GetSubName3()
-{
-	return iSubName3;
-}
-
-/**
-Function responsible to set SubName3
-
-@internalComponent
-@released
-
-@param aSubName3 - a long entry sub name 3
-*/
-void CLongEntry::SetSubName3(String aSubName3)
-{
-	iSubName3 = aSubName3;
-}
-
-/**
-Function responsible to return attribute
-
-@internalComponent
-@released
-
-@return iAttribute - returns a long entry attribute
-*/
-char CLongEntry::GetAttribute() const
-{
-	return iAttribute;
-}
-
-/**
-Function responsible to return check sum
-
-@internalComponent
-@released
-
-@return iCheckSum - returns long entry check sum
-*/
-char CLongEntry::GetCheckSum() const
-{
-	return iCheckSum;
-}
-
-/**
-Function responsible to return Dir Type
-
-@internalComponent
-@released
-
-@return iDirType - returns long entry dir type
-*/
-char CLongEntry::GetDirType() const
-{
-	return iDirType;
-}
-
-/**
-Function responsible to return Low cluster number
-
-@internalComponent
-@released
-
-@return iFirstClusterNumberLow - returns Low cluster number
-*/
-unsigned short int CLongEntry::GetClusterNumberLow() const
-{
-	return iFirstClusterNumberLow;
-}
+/*
+* 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 class provides the basic set and get operations associated 
+* with longentry attributes.
+* @internalComponent
+* @released
+*
+*/
+
+
+#include "longentry.h"
+
+/**
+Constructor responsible to initialze the possible attributes of 
+long entry
+
+@internalComponent
+@released
+
+@param aChckSum - Short entry checksum value
+*/
+
+CLongEntry::CLongEntry(	char aChckSum):
+						iDirOrder(0),
+						iAttribute(EAttrLongName),
+						iDirType(KDirSubComponent),
+						iCheckSum(aChckSum),
+						iFirstClusterNumberLow(0)						
+{
+}
+
+/**
+Destructor:
+
+@internalComponent
+@released
+
+*/
+CLongEntry::~CLongEntry()
+{
+}
+
+/**
+Function responsible to return Directory entry Order
+
+@internalComponent
+@released
+
+@return iDirOrder - Long name sub entry order
+*/
+char CLongEntry::GetDirOrder() const
+{
+	return iDirOrder;
+}
+
+/**
+Function responsible to initialize Directory entry Order
+
+@internalComponent
+@released
+
+@param aDirOrder - Long name sub entry order
+*/
+void CLongEntry::SetDirOrder(char aDirOrder)
+{
+	iDirOrder = aDirOrder;
+}
+
+/**
+Function responsible to return SubName1
+
+@internalComponent
+@released
+
+@return iSubName1 - returns sub name 1 of a long entry
+*/
+string& CLongEntry::GetSubName1()
+{
+	return iSubName1;
+}
+
+/**
+Function responsible to set SubName3
+
+@internalComponent
+@released
+
+@param aSubName1 - a long entry sub name 1
+*/
+void CLongEntry::SetSubName1(string aSubName1)
+{
+	iSubName1 = aSubName1;
+}
+
+/**
+Function responsible to return SubName2
+
+@internalComponent
+@released
+
+@return iSubName2 - returns sub name 2 of a long entry
+*/
+string& CLongEntry::GetSubName2()
+{
+	return iSubName2;
+}
+
+/**
+Function responsible to set SubName2
+
+@internalComponent
+@released
+
+@param aSubName2 - a long entry sub name 2
+*/
+void CLongEntry::SetSubName2(string aSubName2)
+{
+	iSubName2 = aSubName2;
+}
+
+/**
+Function responsible to return SubName3
+
+@internalComponent
+@released
+
+@return iSubName3 - returns sub name 3 of a long entry
+*/
+string& CLongEntry::GetSubName3()
+{
+	return iSubName3;
+}
+
+/**
+Function responsible to set SubName3
+
+@internalComponent
+@released
+
+@param aSubName3 - a long entry sub name 3
+*/
+void CLongEntry::SetSubName3(string aSubName3)
+{
+	iSubName3 = aSubName3;
+}
+
+/**
+Function responsible to return attribute
+
+@internalComponent
+@released
+
+@return iAttribute - returns a long entry attribute
+*/
+char CLongEntry::GetAttribute() const
+{
+	return iAttribute;
+}
+
+/**
+Function responsible to return check sum
+
+@internalComponent
+@released
+
+@return iCheckSum - returns long entry check sum
+*/
+char CLongEntry::GetCheckSum() const
+{
+	return iCheckSum;
+}
+
+/**
+Function responsible to return Dir Type
+
+@internalComponent
+@released
+
+@return iDirType - returns long entry dir type
+*/
+char CLongEntry::GetDirType() const
+{
+	return iDirType;
+}
+
+/**
+Function responsible to return Low cluster number
+
+@internalComponent
+@released
+
+@return iFirstClusterNumberLow - returns Low cluster number
+*/
+unsigned short int CLongEntry::GetClusterNumberLow() const
+{
+	return iFirstClusterNumberLow;
+}
--- a/imgtools/imglib/filesystem/source/longname.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/source/longname.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,458 +1,462 @@
-/*
-* 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: 
-* Receives the long file name and prepares short and long directory 
-* entries.
-* @internalComponent
-* @released
-*
-*/
-
-
-#include "longname.h"
-
-
-/** 
-Constructor: Responsible to create 
-1. Short entry
-2. Sub components of long entry name as per microsoft FAT spec.
-
-@internalComponent
-@released
-
-@param aClusterPtr - Cluster instance address
-@param aEntry - CDirectory class pointer
-*/
-
-ClongName::ClongName(CCluster* aClusterPtr,
-					 CDirectory* aEntry):
-					 iClusterPtr(aClusterPtr),
-					 iTildeNumberPosition(ETildeNumberPosition),
-					 iSubNameProperEnd(false),
-					 iFirstNullName(false)
-{
-	iLongName = aEntry->GetEntryName();
-	iLongEntryAttribute = aEntry->GetEntryAttribute();
-	iClusterNumber = aClusterPtr->GetCurrentClusterNumber();
-	iLongNameLength = iLongName.length();
-	if(iLongNameLength == 0)
-	{
-		throw ErrorHandler(EMPTYFILENAME, __FILE__, __LINE__);
-	}
-	FormatLongFileName(iLongName);
-	iShortName = GetShortEntryName();
-	GShortEntryList.push_back(iShortName);
-}
-
-
-/**
-Static function to clear the strings stored in static Global Stringlist
-
-@internalComponent
-@released
-*/
-void ClongName::DestroyShortEntryList()
-{
-	GShortEntryList.clear();
-}
-
-/**
-Destructor: To clear the contents from the STL containers in any exception case.
-In normal case the containers are cleared once its usage is finished
-
-@internalComponent
-@released
-*/
-
-ClongName::~ClongName()
-{
-	iSubNamesList.clear();
-	while(iLongEntryStack.size() > 0)
-	{
-		delete iLongEntryStack.top();
-		iLongEntryStack.pop();
-	}
-	/* Cluster instance should be deleted only by dirregion, So just assign 
-	 * NULL value to the pointer
-	 */
-	iClusterPtr = NULL;
-}
-
-/**
-Function takes a long entry and writes all of the attributes into iLongNameEntryString.
-To write the sub name's in a formatted WriteSubName() function invoked
-
-@internalComponent
-@released
-
-@param aLongEntry - the long entry
-*/
-void ClongName::WriteLongEntry(CLongEntry* aLongEntry,String& longEntryString)
-{
-	longEntryString.append(KWriteOnce, aLongEntry->GetDirOrder());
-	WriteSubName(aLongEntry->GetSubName1(),(ESubName1Length*2),longEntryString);
-	longEntryString.append(KWriteOnce, aLongEntry->GetAttribute());
-	longEntryString.append(KWriteOnce, aLongEntry->GetDirType());
-	longEntryString.append(KWriteOnce, aLongEntry->GetCheckSum());
-	WriteSubName(aLongEntry->GetSubName2(),(ESubName2Length*2),longEntryString);
-	unsigned short int lowClusterNumber = aLongEntry->GetClusterNumberLow();
-	longEntryString.append(ToString(lowClusterNumber));
-	WriteSubName(aLongEntry->GetSubName3(),(ESubName3Length*2),longEntryString);
-}
-
-/**
-Function responsible to 
-1. Write the sub name of the long entry, every character splitted by '.'(00)
-2. If the name is not multiple of 13 this function applies NULL character padding and 
-   padding with 'FF'.
-
-@internalComponent
-@released
-
-@param aName - Sub name of a long entry
-@param aSubNameLength - No of characters to be filled
-@param alongEntryString - formatted sub name appended to this string
-*/
-void ClongName::WriteSubName(String& aSubName,unsigned short aSubNameLength,String& alongEntryString)
-{
-	unsigned int subNameCurrLength = aSubName.length();
-	if(subNameCurrLength == 0)
-	{
-		iFirstNullName = true;
-	}
-	else
-	{
-		iFirstNullName = false;
-	}
-	unsigned int beginIndex = 1;
-	if(subNameCurrLength > 0)
-	{
-		//Insert zero between every character, as per FAT spec requirement
-		while(subNameCurrLength > 0)
-		{
-			aSubName.insert(beginIndex,1,0); //Insert zero once
-			beginIndex += 2; //Jump 2 characters
-			--subNameCurrLength;
-		}
-		subNameCurrLength = aSubName.length();
-		if(subNameCurrLength == aSubNameLength)
-		{
-			iSubNameProperEnd = true;
-		}
-		//Apply padding with two zero's to mention Long Name end.
-		if(subNameCurrLength < aSubNameLength)
-		{
-			aSubName.insert(subNameCurrLength, KPaddingCharCnt, 0); 
-		}
-	}
-	subNameCurrLength = aSubName.length();
-	if((iSubNameProperEnd == true) && (iFirstNullName == true))
-	{
-		aSubName.insert(subNameCurrLength, KPaddingCharCnt, 0);
-		iSubNameProperEnd = false;
-		iFirstNullName = false;
-	}
-	subNameCurrLength = aSubName.length();
-	//Insert FF for all unfilled characters.
-	if(subNameCurrLength < aSubNameLength)
-	{
-			aSubName.insert(subNameCurrLength,(aSubNameLength - subNameCurrLength),
-							KLongNamePaddingChar);
-	}
-	alongEntryString.append(aSubName.c_str(),aSubName.length());
-}
-
-/**
-Function responsible to push the string into iNameList container and to erase the input
-strings data
-
-@internalComponent
-@released
-
-@param aFirstName - first sub name
-@param aSecondName - Second sub name
-@param aThirdName - third sub name
-*/
-void ClongName::PushAndErase(String& aFirstName,String& aSecondName,String& aThirdName)
-{
-	iSubNamesList.push_back(aFirstName);
-	aFirstName.erase();
-	iSubNamesList.push_back(aSecondName);
-	aSecondName.erase();
-	iSubNamesList.push_back(aThirdName);
-	aThirdName.erase();
-}
-
-/**
-Function responsible split single sub name from the long name
-
-@internalComponent
-@released
-
-@param aLongName - The long name need to be splitted
-@param aStartIndex - Sub name starting index
-@param aStringLength - total string length
-@param aSubNameLength - Length of the Sub Name of required length
-@param aSubName - splitted Sub Name assigned using this string
-*/
-void ClongName::GetSubName(String& aLongName,
-						   int& aStartIndex,
-						   int& aStringLength,
-						   int aSubNameLength,
-						   String& aSubName)
-{
-	if((aStartIndex + aSubNameLength) <= aStringLength)
-	{
-		aSubName = aLongName.substr(aStartIndex,aSubNameLength);
-		aStartIndex += aSubNameLength;
-		return;
-	}
-	aSubName = aLongName.substr(aStartIndex);
-	aStartIndex += aSubName.length();
-}
-
-/** 
-Function to split the long file name into smaller sub names,such as it should be 
-written into long directory entries. All splitted names are pushed into the 
-iNameList container.
-
-@internalComponent
-@released
-*/
-void ClongName::FormatLongFileName(String& aLongName)
-{
-	int stringLength = aLongName.length();
-	int startIndex = 0;
-	String iSubName1;
-	String iSubName2;
-	String iSubName3;
-
-	while(startIndex < stringLength)
-	{
-		GetSubName(aLongName,startIndex,stringLength,ESubName1Length,iSubName1);
-		GetSubName(aLongName,startIndex,stringLength,ESubName2Length,iSubName2);
-		GetSubName(aLongName,startIndex,stringLength,ESubName3Length,iSubName3);
-		PushAndErase(iSubName1,iSubName2,iSubName3);
-	}
-}
-
-/**
-Function responsible to create new short name if the currently generated short name 
-already exists. 
-
-eg. Input:UNITTE~1TXT returns:UNITTE~2TXT
-
-@internalComponent
-@released
-
-@return - returns the short name
-*/
-void ClongName::CheckAndUpdateShortName(String& aShortName)
-{
-	char trailingChar;
-	StringList::iterator beginIter = GShortEntryList.begin();
-	StringList::iterator endIter = GShortEntryList.end();
-	String tempString;
-	while(beginIter != endIter)
-	{
-		tempString = (*beginIter);
-		if(strcmp(tempString.c_str(),aShortName.c_str()) == 0)
-		{
-			trailingChar = aShortName.at(iTildeNumberPosition);
-			aShortName[iTildeNumberPosition] = ++trailingChar; //Increment the character value by 1
-			continue;
-		}
-		++beginIter;
-	}
-}
-
-/**
-Function responsible to take the long file name as input and to prepare the short name.
-e.g. Long File Name.pl to LONGFI~1PL
-
-@internalComponent
-@released
-
-@return - returns the short name
-*/
-
-String ClongName::GetShortEntryName()
-{
-	String shortName;
-	unsigned int extensionIndex = iLongName.find_last_of(KDot);
-
-	unsigned int dotIndex = extensionIndex;
-	//Erase all the dots from the string, but keep the extension index 
-	while(dotIndex != String::npos)
-	{
-		iLongName.erase(dotIndex,1); //Erase the dot
-		dotIndex = iLongName.find_first_of(KDot);
-		if(dotIndex != String::npos)
-		{
-			//Decrement only if more than one dot exists
-			--extensionIndex;
-		}
-	}
-
-	if((iLongEntryAttribute & EAttrDirectory)== 0) 
-	{
-		if(extensionIndex <= EShortNameInitialLength)
-		{
-			//if the full name length is less than 6 characters, assign the whole name
-			shortName.assign(iLongName.c_str(),extensionIndex);
-		}
-		else
-		{
-			shortName.assign(iLongName.c_str(),EShortNameInitialLength);
-		}
-		//+1 is added to get '~' symbol position
-		iTildeNumberPosition = shortName.length() + 1;
-	}
-	else
-	{
-		shortName.assign(iLongName.c_str(),EShortNameInitialLength);
-	}
-	shortName += KTilde;
-	shortName += KTildeNumber;
-	shortName.assign(ToUpper(shortName));
-	if(extensionIndex <  iLongName.length()) //to identify whether the name has any extension.
-	{
-		if(shortName.length() < ENameLength)
-		{
-			shortName.append((ENameLength - shortName.length()),KSpace);
-		}
-		String shortNameString = iLongName.substr(extensionIndex,EExtensionLength);
-		shortName.append(ToUpper(shortNameString));
-		CheckAndUpdateShortName(shortName);
-		return shortName;
-	}
-	//extension padding
-	shortName.append(EExtensionLength,KSpace);
-	CheckAndUpdateShortName(shortName);
-	return shortName;
-}
-
-/**
-Function takes the short entry name as input and calculates checksum as per the 
-Microsoft FAT spec.
-
-@internalComponent
-@released
-
-@return - returns checkSum
-*/
-
-unsigned char ClongName::CalculateCheckSum()
-{
-	char* tempShortNamePtr = (char*)iShortName.c_str();
-	unsigned short int nameLength = 0;
-	unsigned char chckSum = '\0';
-	for(nameLength = ENameLengthWithExtension; nameLength != 0; nameLength--)
-	{
-		chckSum = ((chckSum & 1) ? 0x80 : NULL) + (chckSum >>1) + *tempShortNamePtr++;
-	}
-	return chckSum;
-}
-
-/**
-Function responsible to initialize short entry attributes.
-Short entry is also an sub entry along with Long entries
-
-@internalComponent
-@released
-
-@param aEntry - directory entry which has long file name
-@return shortEntry - returns the initialized short Directory entry
-*/
-CDirectory* ClongName::CreateShortEntry(CDirectory* aEntry)
-{
-	CDirectory* shortEntry = new CDirectory((char*)iShortName.c_str());
-	shortEntry->SetEntryAttribute(aEntry->GetEntryAttribute()); 
-	if(aEntry->IsFile())
-	{	 
-		shortEntry->SetFilePath((char*)aEntry->GetFilePath().c_str());
-	}
-	shortEntry->SetFileSize(aEntry->GetFileSize());
-	/** Initialize the cluster number variables by splitting high and low words of
-	current cluster number
-	*/
-	shortEntry->SetClusterNumberHi((unsigned short)(iClusterNumber >> KBitShift16));
-	shortEntry->SetClusterNumberLow((unsigned short)(iClusterNumber & KHighWordMask));
-	return shortEntry;
-}
-
-/**
-Function responsible
-1. To erase the string from the iNameList container.
-2. To pop out the element
-
-@internalComponent
-@released
-*/
-void ClongName::PopAndErase()
-{
-	iSubNamesList.front().erase();
-	iSubNamesList.pop_front();
-}
-
-/** 
-Function responsible to 
-1. Pop all the name's 3 by 3 from iNameList container
-2. Construct long name directory entries
-3. Push the long entries into iLongEntryStack 
-4. finally create Long name sub entries as string and append it to longEntryString.
-
-@internalComponent
-@released
-
-@return - returns the formatted long name string
-*/
-String ClongName::CreateLongEntries()
-{
-	String longEntryString;
-	CLongEntry* longEntryObject;
-	unsigned char chckSum = CalculateCheckSum();
-	unsigned char dirOrderNumber = 0x00;
-	while(iSubNamesList.size() > 0)
-	{
-		longEntryObject = new CLongEntry(chckSum);
-		longEntryObject->SetSubName1(iSubNamesList.front());
-		PopAndErase();
-		longEntryObject->SetSubName2(iSubNamesList.front());
-		PopAndErase();
-		longEntryObject->SetSubName3(iSubNamesList.front());
-		PopAndErase();
-		longEntryObject->SetDirOrder(++dirOrderNumber);
-	
-		iLongEntryStack.push(longEntryObject);
-	}
-
-	bool lastLongEntry = true;
-	while(iLongEntryStack.size() > 0)
-	{
-		if(lastLongEntry == true)
-		{
-			longEntryObject = iLongEntryStack.top();
-			/* As per Microsoft FAT spec, Last sub entry of Long name Directory Order attribute
-			 * should be logically OR'ed with value '0x40'
-			 */
-			longEntryObject->SetDirOrder(longEntryObject->GetDirOrder() | ELastLongEntry);
-			lastLongEntry = false;
-		}
-		WriteLongEntry(iLongEntryStack.top(),longEntryString);
-		delete iLongEntryStack.top();
-		iLongEntryStack.pop();
-	}
-	return longEntryString;
-}
+/*
+* 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: 
+* Receives the long file name and prepares short and long directory 
+* entries.
+* @internalComponent
+* @released
+*
+*/
+
+
+#include "longname.h"
+
+
+/** 
+Constructor: Responsible to create 
+1. Short entry
+2. Sub components of long entry name as per microsoft FAT spec.
+
+@internalComponent
+@released
+
+@param aClusterPtr - Cluster instance address
+@param aEntry - CDirectory class pointer
+*/
+
+ClongName::ClongName(CCluster* aClusterPtr,
+					 CDirectory* aEntry):
+					 iClusterPtr(aClusterPtr),
+					 iTildeNumberPosition(ETildeNumberPosition),
+					 iSubNameProperEnd(false),
+					 iFirstNullName(false)
+{
+	iLongName = aEntry->GetEntryName();
+	iLongEntryAttribute = aEntry->GetEntryAttribute();
+	iClusterNumber = aClusterPtr->GetCurrentClusterNumber();
+	iLongNameLength = iLongName.length();
+	if(iLongNameLength == 0)
+	{
+		throw ErrorHandler(EMPTYFILENAME, __FILE__, __LINE__);
+	}
+	FormatLongFileName(iLongName);
+	iShortName = GetShortEntryName();
+	GShortEntryList.push_back(iShortName);
+}
+
+
+/**
+Static function to clear the strings stored in static Global Stringlist
+
+@internalComponent
+@released
+*/
+void ClongName::DestroyShortEntryList()
+{
+	GShortEntryList.clear();
+}
+
+/**
+Destructor: To clear the contents from the STL containers in any exception case.
+In normal case the containers are cleared once its usage is finished
+
+@internalComponent
+@released
+*/
+
+ClongName::~ClongName()
+{
+	iSubNamesList.clear();
+	while(iLongEntryStack.size() > 0)
+	{
+		delete iLongEntryStack.top();
+		iLongEntryStack.pop();
+	}
+	/* Cluster instance should be deleted only by dirregion, So just assign 
+	 * NULL value to the pointer
+	 */
+	iClusterPtr = NULL;
+}
+
+/**
+Function takes a long entry and writes all of the attributes into iLongNameEntryString.
+To write the sub name's in a formatted WriteSubName() function invoked
+
+@internalComponent
+@released
+
+@param aLongEntry - the long entry
+*/
+void ClongName::WriteLongEntry(CLongEntry* aLongEntry,string& longEntryString)
+{
+	longEntryString.append(KWriteOnce, aLongEntry->GetDirOrder());
+	WriteSubName(aLongEntry->GetSubName1(),(ESubName1Length*2),longEntryString);
+	longEntryString.append(KWriteOnce, aLongEntry->GetAttribute());
+	longEntryString.append(KWriteOnce, aLongEntry->GetDirType());
+	longEntryString.append(KWriteOnce, aLongEntry->GetCheckSum());
+	WriteSubName(aLongEntry->GetSubName2(),(ESubName2Length*2),longEntryString);
+	unsigned short int lowClusterNumber = aLongEntry->GetClusterNumberLow();
+	longEntryString.append(ToString(lowClusterNumber));
+	WriteSubName(aLongEntry->GetSubName3(),(ESubName3Length*2),longEntryString);
+}
+
+/**
+Function responsible to 
+1. Write the sub name of the long entry, every character splitted by '.'(00)
+2. If the name is not multiple of 13 this function applies NULL character padding and 
+   padding with 'FF'.
+
+@internalComponent
+@released
+
+@param aName - Sub name of a long entry
+@param aSubNameLength - No of characters to be filled
+@param alongEntryString - formatted sub name appended to this string
+*/
+void ClongName::WriteSubName(string& aSubName,unsigned short aSubNameLength,string& alongEntryString)
+{
+	unsigned int subNameCurrLength = aSubName.length();
+	if(subNameCurrLength == 0)
+	{
+		iFirstNullName = true;
+	}
+	else
+	{
+		iFirstNullName = false;
+	}
+	unsigned int beginIndex = 1;
+	if(subNameCurrLength > 0)
+	{
+		//Insert zero between every character, as per FAT spec requirement
+		while(subNameCurrLength > 0)
+		{
+			aSubName.insert(beginIndex,1,0); //Insert zero once
+			beginIndex += 2; //Jump 2 characters
+			--subNameCurrLength;
+		}
+		subNameCurrLength = aSubName.length();
+		if(subNameCurrLength == aSubNameLength)
+		{
+			iSubNameProperEnd = true;
+		}
+		//Apply padding with two zero's to mention Long Name end.
+		if(subNameCurrLength < aSubNameLength)
+		{
+			aSubName.insert(subNameCurrLength, KPaddingCharCnt, 0); 
+			iSubNameProperEnd = false;
+		}
+	}
+	subNameCurrLength = aSubName.length();
+	if((iSubNameProperEnd == true) && (iFirstNullName == true))
+	{
+		aSubName.insert(subNameCurrLength, KPaddingCharCnt, 0);
+		iSubNameProperEnd = false;
+		iFirstNullName = false;
+	}
+	subNameCurrLength = aSubName.length();
+	//Insert FF for all unfilled characters.
+	if(subNameCurrLength < aSubNameLength)
+	{
+			aSubName.insert(subNameCurrLength,(aSubNameLength - subNameCurrLength),
+							KLongNamePaddingChar);
+	}
+	alongEntryString.append(aSubName.c_str(),aSubName.length());
+}
+
+/**
+Function responsible to push the string into iNameList container and to erase the input
+strings data
+
+@internalComponent
+@released
+
+@param aFirstName - first sub name
+@param aSecondName - Second sub name
+@param aThirdName - third sub name
+*/
+void ClongName::PushAndErase(string& aFirstName,string& aSecondName,string& aThirdName)
+{
+	iSubNamesList.push_back(aFirstName);
+	aFirstName.erase();
+	iSubNamesList.push_back(aSecondName);
+	aSecondName.erase();
+	iSubNamesList.push_back(aThirdName);
+	aThirdName.erase();
+}
+
+/**
+Function responsible split single sub name from the long name
+
+@internalComponent
+@released
+
+@param aLongName - The long name need to be splitted
+@param aStartIndex - Sub name starting index
+@param aStringLength - total string length
+@param aSubNameLength - Length of the Sub Name of required length
+@param aSubName - splitted Sub Name assigned using this string
+*/
+void ClongName::GetSubName(string& aLongName,
+						   int& aStartIndex,
+						   int& aStringLength,
+						   int aSubNameLength,
+						   string& aSubName)
+{
+	if((aStartIndex + aSubNameLength) <= aStringLength)
+	{
+		aSubName = aLongName.substr(aStartIndex,aSubNameLength);
+		aStartIndex += aSubNameLength;
+		return;
+	}
+	aSubName = aLongName.substr(aStartIndex);
+	aStartIndex += aSubName.length();
+}
+
+/** 
+Function to split the long file name into smaller sub names,such as it should be 
+written into long directory entries. All splitted names are pushed into the 
+iNameList container.
+
+@internalComponent
+@released
+*/
+void ClongName::FormatLongFileName(string& aLongName)
+{
+	int stringLength = aLongName.length();
+	int startIndex = 0;
+	string iSubName1;
+	string iSubName2;
+	string iSubName3;
+
+	while(startIndex < stringLength)
+	{
+		GetSubName(aLongName,startIndex,stringLength,ESubName1Length,iSubName1);
+		GetSubName(aLongName,startIndex,stringLength,ESubName2Length,iSubName2);
+		GetSubName(aLongName,startIndex,stringLength,ESubName3Length,iSubName3);
+		PushAndErase(iSubName1,iSubName2,iSubName3);
+	}
+}
+
+/**
+Function responsible to create new short name if the currently generated short name 
+already exists. 
+
+eg. Input:UNITTE~1TXT returns:UNITTE~2TXT
+
+@internalComponent
+@released
+
+@return - returns the short name
+*/
+void ClongName::CheckAndUpdateShortName(string& aShortName)
+{
+	char trailingChar;
+	StringList::iterator beginIter = GShortEntryList.begin();
+	StringList::iterator endIter = GShortEntryList.end();
+	string tempString;
+	while(beginIter != endIter)
+	{
+		tempString = (*beginIter);
+		if(strcmp(tempString.c_str(),aShortName.c_str()) == 0)
+		{
+			trailingChar = aShortName.at(iTildeNumberPosition);
+			aShortName[iTildeNumberPosition] = ++trailingChar; //Increment the character value by 1
+			continue;
+		}
+		++beginIter;
+	}
+        int gap = ENameLengthWithExtension - aShortName.length();
+        if(gap >0 )
+            aShortName.append(gap,KSpace);
+}
+
+/**
+Function responsible to take the long file name as input and to prepare the short name.
+e.g. Long File Name.pl to LONGFI~1PL
+
+@internalComponent
+@released
+
+@return - returns the short name
+*/
+
+string ClongName::GetShortEntryName()
+{
+	string shortName;
+	unsigned int extensionIndex = iLongName.find_last_of(KDot);
+
+	unsigned int dotIndex = extensionIndex;
+	//Erase all the dots from the string, but keep the extension index 
+	while(dotIndex != string::npos)
+	{
+		iLongName.erase(dotIndex,1); //Erase the dot
+		dotIndex = iLongName.find_first_of(KDot);
+		if(dotIndex != string::npos)
+		{
+			//Decrement only if more than one dot exists
+			--extensionIndex;
+		}
+	}
+
+	if((iLongEntryAttribute & EAttrDirectory)== 0) 
+	{
+		if(extensionIndex <= EShortNameInitialLength)
+		{
+			//if the full name length is less than 6 characters, assign the whole name
+			shortName.assign(iLongName.c_str(),extensionIndex);
+		}
+		else
+		{
+			shortName.assign(iLongName.c_str(),EShortNameInitialLength);
+		}
+		//+1 is added to get '~' symbol position
+		iTildeNumberPosition = shortName.length() + 1;
+	}
+	else
+	{
+		shortName.assign(iLongName.c_str(),EShortNameInitialLength);
+	}
+	shortName += KTilde;
+	shortName += KTildeNumber;
+	shortName.assign(ToUpper(shortName));
+	if(extensionIndex <  iLongName.length()) //to identify whether the name has any extension.
+	{
+		if(shortName.length() < ENameLength)
+		{
+			shortName.append((ENameLength - shortName.length()),KSpace);
+		}
+		string shortNameString = iLongName.substr(extensionIndex,EExtensionLength);
+		shortName.append(ToUpper(shortNameString));
+		CheckAndUpdateShortName(shortName);
+		return shortName;
+	}
+	//extension padding
+	shortName.append(EExtensionLength,KSpace);
+	CheckAndUpdateShortName(shortName);
+	return shortName;
+}
+
+/**
+Function takes the short entry name as input and calculates checksum as per the 
+Microsoft FAT spec.
+
+@internalComponent
+@released
+
+@return - returns checkSum
+*/
+
+unsigned char ClongName::CalculateCheckSum()
+{
+	char* tempShortNamePtr = (char*)iShortName.c_str();
+	unsigned short int nameLength = 0;
+	unsigned char chckSum = '\0';
+	for(nameLength = ENameLengthWithExtension; nameLength != 0; nameLength--)
+	{
+		chckSum = ((chckSum & 1) ? 0x80 : NULL) + (chckSum >>1) + *tempShortNamePtr++;
+	}
+	return chckSum;
+}
+
+/**
+Function responsible to initialize short entry attributes.
+Short entry is also an sub entry along with Long entries
+
+@internalComponent
+@released
+
+@param aEntry - directory entry which has long file name
+@return shortEntry - returns the initialized short Directory entry
+*/
+CDirectory* ClongName::CreateShortEntry(CDirectory* aEntry)
+{
+	CDirectory* shortEntry = new CDirectory(iShortName.c_str(),NULL);
+	shortEntry->SetEntryAttribute(aEntry->GetEntryAttribute()); 
+	if(aEntry->IsFile())
+	{	 
+		shortEntry->SetFilePath((char*)aEntry->GetFilePath().c_str());
+	}
+	shortEntry->SetFileSize(aEntry->GetFileSize());
+	/** Initialize the cluster number variables by splitting high and low words of
+	current cluster number
+	*/
+	shortEntry->SetClusterNumberHi((unsigned short)(iClusterNumber >> KBitShift16));
+	shortEntry->SetClusterNumberLow((unsigned short)(iClusterNumber & KHighWordMask));
+	return shortEntry;
+}
+
+/**
+Function responsible
+1. To erase the string from the iNameList container.
+2. To pop out the element
+
+@internalComponent
+@released
+*/
+void ClongName::PopAndErase()
+{
+	iSubNamesList.front().erase();
+	iSubNamesList.pop_front();
+}
+
+/** 
+Function responsible to 
+1. Pop all the name's 3 by 3 from iNameList container
+2. Construct long name directory entries
+3. Push the long entries into iLongEntryStack 
+4. finally create Long name sub entries as string and append it to longEntryString.
+
+@internalComponent
+@released
+
+@return - returns the formatted long name string
+*/
+string ClongName::CreateLongEntries()
+{
+	string longEntryString;
+	CLongEntry* longEntryObject;
+	unsigned char chckSum = CalculateCheckSum();
+	unsigned char dirOrderNumber = 0x00;
+	while(iSubNamesList.size() > 0)
+	{
+		longEntryObject = new CLongEntry(chckSum);
+		longEntryObject->SetSubName1(iSubNamesList.front());
+		PopAndErase();
+		longEntryObject->SetSubName2(iSubNamesList.front());
+		PopAndErase();
+		longEntryObject->SetSubName3(iSubNamesList.front());
+		PopAndErase();
+		longEntryObject->SetDirOrder(++dirOrderNumber);
+	
+		iLongEntryStack.push(longEntryObject);
+	}
+
+	bool lastLongEntry = true;
+	while(iLongEntryStack.size() > 0)
+	{
+		if(lastLongEntry == true)
+		{
+			longEntryObject = iLongEntryStack.top();
+			/* As per Microsoft FAT spec, Last sub entry of Long name Directory Order attribute
+			 * should be logically OR'ed with value '0x40'
+			 */
+			longEntryObject->SetDirOrder(longEntryObject->GetDirOrder() | ELastLongEntry);
+			lastLongEntry = false;
+		}
+		WriteLongEntry(iLongEntryStack.top(),longEntryString);
+		delete iLongEntryStack.top();
+		iLongEntryStack.pop();
+	}
+	return longEntryString;
+}
--- a/imgtools/imglib/filesystem/source/messageimplementation.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/filesystem/source/messageimplementation.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,244 +1,241 @@
-/*
-* 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 class is used get the message strings and provides operations 
-* to log them into log file
-* @internalComponent
-* @released
-*
-*/
-
-
-
-#include "messageimplementation.h"
-#include "errorhandler.h"
-
-using std::endl;
-using std::cout;
-typedef std::string String;
-
-char *errorMssgPrefix="FileSystem : Error:";
-char *warnMssgPrefix="FileSystem : Warning:";
-char *infoMssgPrefix="FileSystem : Information:";
-char *Space=" ";
-
-enum MessageArraySize{MAX=16};
-
-//Messages stored required for the program
-struct EnglishMessage MessageArray[MAX]=
-{
-	{FILEOPENERROR,"%s:%d: Could not open file : %s."},
-	{FILEREADERROR,"%s:%d: Could not read file : %s."},
-	{FILEWRITEERROR,"%s:%d: Could not write input image file."},
-	{MEMORYALLOCATIONERROR,"%s:%d: Memory allocation failure."},
-	{ENTRYCREATEMSG,"Creating the entry : %s."},
-	{BOOTSECTORERROR,"%s:%d: Boot Sector Error: %s."},
-	{BOOTSECTORCREATEMSG,"Creating bootsector : %s."},
-	{BOOTSECTORWRITEMSG,"Writing bootsector : %s"},
-	{FATTABLEWRITEMSG, "Writing FAT table for : %s"},
-	{IMAGESIZETOOBIG,"%s:%d: Current image size is greater than the given partition size: %s"},
-	{NOENTRIESFOUND,"%s:%d: No entries found under root."},
-	{EMPTYFILENAME,"%s:%d: Empty name received."},
-	{EMPTYSHORTNAMEERROR,"%s:%d: Empty short name."},
-	{CLUSTERERROR,"%s:%d: Cluster Instance error."},
-	{ROOTNOTFOUND,"%s:%d: None of the entries received."},
-	{UNKNOWNERROR,"%s:%d: Unknown exception occured."}
-};
-
-/**
-Constructor to reset the logging option flag.
-
-@internalComponent
-@released
-*/
-MessageImplementation::MessageImplementation()
-{
-    iLogging = false;
-}
-
-/**
-Destructor to close log file if logging is enabled and to clear the messaged.
-
-@internalComponent
-@released
-*/
-MessageImplementation::~MessageImplementation()
-{
-    if(iLogging)
-    {
-		fclose(iLogPtr);
-    }
-	iMessage.clear();
-}
-
-/**
-Function to Get Message stored in map.
-
-@internalComponent
-@released
-
-@param aMessageIndex - Index of the Message to be displayed
-@return Message string to be displayed
-*/
-char * MessageImplementation::GetMessageString(int aMessageIndex)
-{
-	Map::iterator p = iMessage.find(aMessageIndex);
-	if(p != iMessage.end())
-	{
-		return p->second;
-	}
-	else
-	{
-		if(aMessageIndex <= MAX)
-		{
-			return MessageArray[aMessageIndex-1].message;
-		}
-		else
-		{
-			return NULL;
-		}
-	}
-}
-
-/**
-Function to log message in log file if logging is enable.
-
-@internalComponent
-@released
-
-@param aString - Message to be displayed
-*/
-void MessageImplementation::LogOutput(const char *aString)
-{
-    if (iLogging)
-    {
-		fputs(aString,iLogPtr);
-		fputs("\n",iLogPtr);
-    }
-}
-
-
-/**
-Function to display output and log message in log file if logging is enable.
-
-@internalComponent
-@released
-
-@param aString - Message to be displayed
-*/
-void MessageImplementation::Output(const char *aString)
-{
-
-    if (iLogging)
-    {
-		fputs(aString,iLogPtr);
-		fputs("\n",iLogPtr);
-    }
-	cout << aString << endl;
-}
-
-/**
-Function to Get Message stored in map and to display the Message
-
-@internalComponent
-@released
-
-@param aMessageType - The type of the message, whether it is Error or Warning or Information.
-@param aMsgIndex - The index of the information and the corresponding arguments.
-*/
-void MessageImplementation::ReportMessage(int aMessageType, int aMsgIndex,...)
-{
-	String reportMessage;
-	char* ptr;
-
-	va_list ap;
-	va_start(ap,aMsgIndex);
-	
-	ptr = GetMessageString(aMsgIndex);
-	
-	if(ptr)
-	{
-		switch (aMessageType)
-		{
-			case ERROR:
-				reportMessage += errorMssgPrefix;
-				break;
-			case WARNING:
-				reportMessage += warnMssgPrefix;
-				break;
-			case INFORMATION:
-				reportMessage += infoMssgPrefix;
-				break;
-			default:
-				break;
-		}
-		reportMessage += Space;
-		reportMessage.append(ptr);
-		int location = reportMessage.find('%',0);
-		//Erase the string from % to the end, because it is no where required.
-		reportMessage.erase(location);
-		reportMessage += va_arg(ap, char *);
-
-		LogOutput(reportMessage.c_str());
-	}
-}
-
-/**
-Function to start logging.
-
-@internalComponent
-@released
-
-@param aFileName - Name of the Log file
-*/
-void MessageImplementation::StartLogging(char *aFileName)
-{
-	char logFile[1024];
-	FILE *fptr;
-
-	strcpy(logFile,aFileName);
-
-	// open file for log etc.
-	if((fptr=fopen(logFile,"a"))==NULL)
-	{
-		ReportMessage(WARNING, FILEOPENERROR,aFileName);
-	}
-	else
-	{
-	    iLogging = true;
-		iLogPtr=fptr;
-	}
-}
-
-/**
-Function to put Message string in map which is stored in message file.
-If file is not available the put message in map from Message Array structure.
-
-@internalComponent
-@released
-
-@param aFileName - Name of the Message file passed in
-*/
-void MessageImplementation::InitializeMessages()
-{
-	char *errStr;
-	int i;
-
-	for(i=0;i<MAX;i++)
-	{
-		errStr = new char[strlen(MessageArray[i].message) + 1];
-		strcpy(errStr, MessageArray[i].message);
-		iMessage.insert(std::pair<int,char*>(MessageArray[i].index,errStr));
-	}
-}
+/*
+* 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 class is used get the message strings and provides operations 
+* to log them into log file
+* @internalComponent
+* @released
+*
+*/
+
+
+
+#include "messageimplementation.h"
+#include "errorhandler.h"
+
+
+char *errorMssgPrefix="FileSystem : Error:";
+char *warnMssgPrefix="FileSystem : Warning:";
+char *infoMssgPrefix="FileSystem : Information:";
+char *Space=" ";
+
+enum MessageArraySize{MAX=16};
+
+//Messages stored required for the program
+struct EnglishMessage MessageArray[MAX]=
+{
+	{FILEOPENERROR,"%s:%d: Could not open file : %s."},
+	{FILEREADERROR,"%s:%d: Could not read file : %s."},
+	{FILEWRITEERROR,"%s:%d: Could not write input image file."},
+	{MEMORYALLOCATIONERROR,"%s:%d: Memory allocation failure."},
+	{ENTRYCREATEMSG,"Creating the entry : %s."},
+	{BOOTSECTORERROR,"%s:%d: Boot Sector Error: %s."},
+	{BOOTSECTORCREATEMSG,"Creating bootsector : %s."},
+	{BOOTSECTORWRITEMSG,"Writing bootsector : %s"},
+	{FATTABLEWRITEMSG, "Writing FAT table for : %s"},
+	{IMAGESIZETOOBIG,"%s:%d: Current image size is greater than the given partition size: %s"},
+	{NOENTRIESFOUND,"%s:%d: No entries found under root."},
+	{EMPTYFILENAME,"%s:%d: Empty name received."},
+	{EMPTYSHORTNAMEERROR,"%s:%d: Empty short name."},
+	{CLUSTERERROR,"%s:%d: Cluster Instance error."},
+	{ROOTNOTFOUND,"%s:%d: None of the entries received."},
+	{UNKNOWNERROR,"%s:%d: Unknown exception occured."}
+};
+
+/**
+Constructor to reset the logging option flag.
+
+@internalComponent
+@released
+*/
+MessageImplementation::MessageImplementation()
+{
+    iLogging = false;
+}
+
+/**
+Destructor to close log file if logging is enabled and to clear the messaged.
+
+@internalComponent
+@released
+*/
+MessageImplementation::~MessageImplementation()
+{
+    if(iLogging)
+    {
+		fclose(iLogPtr);
+    }
+	iMessage.clear();
+}
+
+/**
+Function to Get Message stored in map.
+
+@internalComponent
+@released
+
+@param aMessageIndex - Index of the Message to be displayed
+@return Message string to be displayed
+*/
+char * MessageImplementation::GetMessageString(int aMessageIndex)
+{
+	Map::iterator p = iMessage.find(aMessageIndex);
+	if(p != iMessage.end())
+	{
+		return p->second;
+	}
+	else
+	{
+		if(aMessageIndex <= MAX)
+		{
+			return MessageArray[aMessageIndex-1].message;
+		}
+		else
+		{
+			return NULL;
+		}
+	}
+}
+
+/**
+Function to log message in log file if logging is enable.
+
+@internalComponent
+@released
+
+@param aString - Message to be displayed
+*/
+void MessageImplementation::LogOutput(const char *aString)
+{
+    if (iLogging)
+    {
+		fputs(aString,iLogPtr);
+		fputs("\n",iLogPtr);
+    }
+}
+
+
+/**
+Function to display output and log message in log file if logging is enable.
+
+@internalComponent
+@released
+
+@param aString - Message to be displayed
+*/
+void MessageImplementation::Output(const char *aString)
+{
+
+    if (iLogging)
+    {
+		fputs(aString,iLogPtr);
+		fputs("\n",iLogPtr);
+    }
+	cout << aString << endl;
+}
+
+/**
+Function to Get Message stored in map and to display the Message
+
+@internalComponent
+@released
+
+@param aMessageType - The type of the message, whether it is Error or Warning or Information.
+@param aMsgIndex - The index of the information and the corresponding arguments.
+*/
+void MessageImplementation::ReportMessage(int aMessageType, int aMsgIndex,...)
+{
+	string reportMessage;
+	char* ptr;
+
+	va_list ap;
+	va_start(ap,aMsgIndex);
+	
+	ptr = GetMessageString(aMsgIndex);
+	
+	if(ptr)
+	{
+		switch (aMessageType)
+		{
+			case ERROR:
+				reportMessage += errorMssgPrefix;
+				break;
+			case WARNING:
+				reportMessage += warnMssgPrefix;
+				break;
+			case INFORMATION:
+				reportMessage += infoMssgPrefix;
+				break;
+			default:
+				break;
+		}
+		reportMessage += Space;
+		reportMessage.append(ptr);
+		int location = reportMessage.find('%',0);
+		//Erase the string from % to the end, because it is no where required.
+		reportMessage.erase(location);
+		reportMessage += va_arg(ap, char *);
+
+		LogOutput(reportMessage.c_str());
+	}
+}
+
+/**
+Function to start logging.
+
+@internalComponent
+@released
+
+@param aFileName - Name of the Log file
+*/
+void MessageImplementation::StartLogging(char *aFileName)
+{
+	char logFile[1024];
+	FILE *fptr;
+
+	strcpy(logFile,aFileName);
+
+	// open file for log etc.
+	if((fptr=fopen(logFile,"a"))==NULL)
+	{
+		ReportMessage(WARNING, FILEOPENERROR,aFileName);
+	}
+	else
+	{
+	    iLogging = true;
+		iLogPtr=fptr;
+	}
+}
+
+/**
+Function to put Message string in map which is stored in message file.
+If file is not available the put message in map from Message Array structure.
+
+@internalComponent
+@released
+
+@param aFileName - Name of the Message file passed in
+*/
+void MessageImplementation::InitializeMessages()
+{
+	char *errStr;
+	int i;
+
+	for(i=0;i<MAX;i++)
+	{
+		errStr = new char[strlen(MessageArray[i].message) + 1];
+		strcpy(errStr, MessageArray[i].message);
+		iMessage.insert(pair<int,char*>(MessageArray[i].index,errStr));
+	}
+}
--- a/imgtools/imglib/group/bld.inf	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/group/bld.inf	Wed Jun 23 16:56:47 2010 +0800
@@ -1,40 +1,68 @@
-/*
-* 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
+filesystem
+uidcrc
--- a/imgtools/imglib/group/filesystem.mmp	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/group/filesystem.mmp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,25 +1,28 @@
-/*
-* 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			libfilesystem.a
-targettype		lib
-sourcepath	../filesystem/source
-source			cluster.cpp directory.cpp dirregion.cpp errorhandler.cpp fat16bootsector.cpp fat16filesystem.cpp fat32bootsector.cpp fat32filesystem.cpp fatbasebootsector.cpp filesysteminterface.cpp longentry.cpp longname.cpp messagehandler.cpp messageimplementation.cpp filesystemclass.cpp
-userinclude	../filesystem/include
-
-option GCC -O2 -Wno-uninitialized
+/*
+* 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			libfilesystem.a
+targettype		lib
+sourcepath	../filesystem/source
+source			cluster.cpp directory.cpp dirregion.cpp errorhandler.cpp fat16bootsector.cpp fat16filesystem.cpp fat32bootsector.cpp fat32filesystem.cpp fatbasebootsector.cpp filesysteminterface.cpp longentry.cpp longname.cpp messagehandler.cpp messageimplementation.cpp filesystemclass.cpp
+userinclude	../filesystem/include
+userinclude	../inc
+
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
+
+option GCC -O2 -Wno-uninitialized
--- a/imgtools/imglib/group/imglib.mrp	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/group/imglib.mrp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/host/h_file.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/host/h_utl.cpp	Wed Jun 23 16:56:47 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/inc/e32image.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/inc/e32image.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/inc/h_utl.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/inc/h_ver.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/inc/pe_file.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/memmap/include/memmap.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/memmap/include/memmaputils.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/memmap/source/memmap.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/memmap/source/memmaputils.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/parameterfileprocessor/include/parameterfileprocessor.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/parameterfileprocessor/source/parameterfileprocessor.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/patchdataprocessor/include/patchdataprocessor.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/imglib/patchdataprocessor/source/patchdataprocessor.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/group/BLD.INF	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/group/readimage.mmp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/group/release.txt	Wed Jun 23 16:56:47 2010 +0800
@@ -1,3680 +1,3826 @@
-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 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/group/romtools.mrp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/maksym/fixupsym.pl	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/maksym/hpsym.pl	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/maksym/maksym.pl	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/maksym/maksymrofs.pl	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/readimage/inc/common.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/readimage/inc/e32_image_reader.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/readimage/inc/image_handler.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/readimage/inc/image_reader.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/readimage/inc/rofs_image_reader.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/readimage/inc/rom_image_reader.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/readimage/src/common.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/readimage/src/e32_image_reader.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/readimage/src/image_handler.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/readimage/src/image_reader.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/readimage/src/rofs_image_reader.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/readimage/src/rom_image_reader.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/r_build.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/r_coreimage.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/r_coreimage.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/r_driveimage.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,569 +1,574 @@
-/*
-* 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>
+
+#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"
+
+
+// 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(const char* aUserFileFormat,enum TFileSystem& aDriveFileFormat)
+	{
+	struct DriveFileFormatSupported* strPointer = iFormatType;
+	for( ; (strPointer->iDriveFileFormat) != '\0' ; ++strPointer )
+		{
+		if(!strcmp(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 ),iParentDirEntry(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); 
+		retStatus = MKDIR(iTempDirName); 
+		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(const char* 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(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(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(const char* aTempDirName)
+	{
+
+	TInt fileDeleted = 1;
+	string dirPath(aTempDirName); 
+	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* parentDirectory = NULL ;
+	if(KNodeTypeChild == aType)
+		parentDirectory = iParentDirEntry;
+	else if(KNodeTypeSibling == aType)
+		parentDirectory = (CDirectory*)(iNodeAddStore[iListReference-1]);
+	
+	CDirectory* iDirectory = new CDirectory(atempnode->iName,parentDirectory);
+	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*)iParentDirEntry);
+			++iListReference;
+			return KErrNone;  
+			}	
+		}
+	else
+		iDirectory->SetEntryAttribute(attrib | EAttrDirectory);
+
+
+	switch(aType)
+		{
+		case KNodeTypeRoot:
+			iDirectory->SetEntryAttribute(EAttrVolumeId);
+			iNodeList.push_back(iDirectory);	
+			iParentDirEntry = iDirectory; 
+			break;
+					
+		case KNodeTypeChild:
+			iNodeAddStore.push_back((void*)iParentDirEntry);
+			++iListReference;
+			parentDirectory->InsertIntoEntryList(iDirectory); 
+			iParentDirEntry = iDirectory ;
+			break;
+
+		case KNodeTypeSibling:
+			parentDirectory->InsertIntoEntryList(iDirectory); 
+			iParentDirEntry = iDirectory ;
+			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;
+	
+	while(node)
+		{
+		// Don't do anything for hidden files.
+		if(node->IsFile() && (!node->iHidden))
+			{
+		
+			TInt32 size=HFile::GetLength(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))
+					{
+					size_t allocSize = size << 1 ;
+					iData = new char[allocSize];
+					if(!iData)
+						return KErrNoMemory;
+					
+					HMem::Set(iData, 0xff, allocSize);
+                    TUint8* aData = (TUint8*)iData;
+					len = node->PlaceFile(aData,0,allocSize,&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";
+	char* fileSourcePath = acurrentNode->iEntry->iName;
+	string newFileName;
+
+	do
+		{
+		newFileName.append(iTempDirName);
+		newFileName.append("/");
+
+		if(!randomValue)	
+			{
+			newFileName.append(fileSourcePath);
+			}
+		else
+			{  
+			newFileName.append(randomString);
+			newFileName.append(fileSourcePath);
+			}
+
+ 
+		ifstream test(newFileName.c_str());
+		if (!test)
+			{
+			test.close();
+			ofstream driveFile(newFileName.c_str(),ios_base::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[ newFileName.length() + 1 ];
+			if(!acurrentNode->iEntry->iFileName)
+				return KErrNoMemory;
+				
+			memcpy(acurrentNode->iEntry->iFileName,newFileName.c_str(),newFileName.length());
+			acurrentNode->iEntry->iFileName[newFileName.length()] = 0;
+			break;
+			}
+
+		test.close();
+		newFileName.erase();
+		++randomValue;
+		sprintf(randomString,"%d",randomValue);
+	
+		}
+	while(randomValue);
+
+	return KErrNone;
+	}
+
+
+
+
--- a/imgtools/romtools/rofsbuild/r_driveimage.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/r_driveimage.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,94 +1,89 @@
-/*
-* 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 "filesysteminterface.h" 
+#include <vector>
+
+typedef vector<void*> EntryReferenceVector;
+typedef	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(const char* alogfile);
+	static TBool FormatTranslation(const char* 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(const 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.
+	CDirectory* iParentDirEntry ;
+
+	// 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
--- a/imgtools/romtools/rofsbuild/r_driveutl.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/r_driveutl.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/r_driveutl.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/r_obey.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,2274 +1,2038 @@
-/*
-* 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 "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.
+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("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"},
+	//	{_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, 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),
+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() {
+	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(iConfigurableFatAttributes)
+		delete iConfigurableFatAttributes;
+	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 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;
+			}
+#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 = 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);
+
+				iConfigurableFatAttributes->iDriveVolumeLabel = volumeLabel.data() ;
+			}
+			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(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));		  
+		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;   
+
+	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;
+	}
+
+	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		
+				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
+			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;
+		}
+		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;
+}
+
+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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/r_obey.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,284 +1,267 @@
-/*
-* 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 <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,
+	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;
+struct ConfigurableFatAttributes;
+
+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;
+	TInt64 iDataSize;
+	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);
+
+	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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/r_rofs.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/r_rofs.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/r_romnode.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/r_smrimage.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/r_smrimage.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/rofsbuild.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,728 +1,677 @@
-/*
-* 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=10;
+static const TInt RofsbuildPatchVersion=4;
+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
+				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]);
+		i++;
+	}
+
+	if (paramFileFlag)
+		return;
+
+	if((gDriveImage == EFalse) && (gSmrImage ==  EFalse) && 
+		(filename.empty() || (gUseCoreImage && gImageFilename.length() == 0))){
+			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(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) {
+				cout << "\nSuccessfully generated the Drive image : " << mainObeyFile->iDriveFileName << "\n";
+			}
+			else {
+				cout << "\nFailed to generate the Image : " << mainObeyFile->iDriveFileName << "\n";
+			}
+			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) {
+				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;
+#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;
+	processCommandLine(argc, argv);
+	//if the user wants to clean up the cache, do it only.
+	if(gCleanCache){
+		try {
+			CacheManager::GetInstance()->CleanCache();
+			printf("Cache has been deleted successfully.\r\n");
+		}
+		catch(CacheException& ce){
+			printf("%s\r\n", ce.GetErrorMessage());
+			return (TInt)1;
+		}
+		return r;
+	}
+	//initialize cache if the user switches on.
+	if(gCache) {
+		try {
+			CacheManager::GetInstance();
+		}
+		catch(CacheException ce){
+			printf("%s\r\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) {
+			printf("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;
+		}
+	}
+	// 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);
+					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 = 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);
+					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 = ptr;
+		} while(temp != 0);
+		gSmrImage = EFalse;
+	}
+	// Process Rofs Obey files.
+	if(obeyFileName) {
+		H.SetLogFile("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
+		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;
+			delete extensionObeyFile;			
+			extensionRofs = 0;
+			extensionObeyFile = 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rofsbuild/rofsbuild.mmp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,61 +1,61 @@
-/*
-* 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
+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 ../../imglib/filesystem/include 
+USERINCLUDE   ../../imglib/patchdataprocessor/include ../../imglib/parameterfileprocessor/include
+USERINCLUDE	  ../../imglib/memmap/include
+USERINCLUDE   ../rofsbuild/inc
+USERINCLUDE   ../../imglib/boostlibrary/
+USERINCLUDE   ../../imglib/boostlibrary/boost
+
+STATICLIBRARY 	filesystem 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_areaset.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_areaset.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_build.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_coreimage.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_coreimage.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_coreimagereader.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_coreimagereader.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_dir.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_dir.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_global.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_global.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_mromimage.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_obey.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_obey.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_rom.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_rom.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_srec.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/r_t_areaset.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/rombuild.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/rombuild.mmp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/romtools/rombuild/rombuild_mingw.mk	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/sisutils/group/sisutils.mmp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/sisutils/group/sisutils.mrp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/sisutils/inc/pkgfileparser.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/sisutils/inc/pkglanguage.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/sisutils/inc/sis2iby.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/sisutils/inc/sisutils.h	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/sisutils/src/pkgfileparser.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/sisutils/src/pkglanguage.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/sisutils/src/sis2iby.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/imgtools/sisutils/src/sisutils.cpp	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/package_definition.xml	Wed Jun 23 16:56:47 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/sbsv2/raptor/bin/buildstats.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/buildstats.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,120 +1,120 @@
-#
-# 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: 
-# Generate some useful statistics from a Raptor build log
-#
-
-import sys
-from  optparse import OptionParser
-from raptorlog import *
-import os
-from stat import *
-import time
-
-def genstats(file, logitems, logdate):
-	bytecount=0.0
-	lastbytecount=0.0
-	print """<?xml version="1.0" encoding="UTF-8"?>
-       <stats xmlns="http://symbian.com/2007/xml/build/raptor/stats"
-       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://symbian.com/2007/xml/build/raptor/stats http://symbian.com/2007/xml/build/raptor/stats1_0.xsd">
-	"""
-
-	if S_ISREG(os.stat(file.name)[ST_MODE]) > 0:
-	 	totalbytes = os.stat(file.name)[ST_SIZE]+0.0
-	else:
-		totalbytes=0.0
-
-	print "<build log='%s' size='%9.0f' date='%s'>" % (file.name,totalbytes,logdate)
-	for l in file.xreadlines():
-		if totalbytes > 0.0:
-			bytecount += len(l)
-			if (bytecount-lastbytecount)/totalbytes > 0.05:
-				lastbytecount = bytecount
-				sys.stderr.write("%3.0f %%" % ((bytecount/totalbytes)*100.0))
-
-		for i in logitems:
-			i.match(l)
-
-	for i in logitems:
-		print i.xml()+"\n"
-		
-	print "</build>"
-	print "</stats>"
-
-
-
-## Command Line Interface ####################################################
-
-parser = OptionParser(prog = "buildstats",
-	usage = "%prog [-h | options] [<file>]")
-
-parser.add_option("-k", "--keep", default = False,
-	 action="store_true", dest="keep", help="Retain matched log lines and display them.") 
-parser.add_option("-d", "--logdate", default = None,
-	 action="store", dest="logdate", help="Specify the date on which the log was started (yyyymmdd).") 
-
-(options, args) = parser.parse_args()
-
-logname="stdin"
-if len(args) > 0:
-	logname=args[0]
-	file = open(logname,"r")
-	if options.logdate != None:
-		logdate = options.logdate
-	else:
-		logdate = time.strftime("%Y%m%d",time.localtime(os.stat(file.name)[ST_CTIME]))
-else:
-	file = sys.stdin
-	logdate = time.strftime("%Y%m%d")
-
-
-if options.keep != False:
-	LogItem.keep = True
-
-
-
-logitems = [ 
-	LogItem("compile attempt", "<compile.*>"), 
-	LogItem("compile success", "<buildstat [^<]*name='compile'[^<]*/>"), 
-	LogItem("compile fail", "<buildstat [^<]*name='failed_compile'[^<]*/>"), 
-	LogItem('link attempt','<link>'), 
-	LogItem("link success", "<buildstat [^<]*name='link'[^<]*/>"), 
-	LogItem("link fail", "<buildstat [^<]*name=.failed_link.[^<]*/>"), 
-	LogItem('postlink attempt','<postlink.*>'), 
-	LogItem("postlink success", "<buildstat [^<]*name=.postlink[^<]*/>"), 
-	LogItem("postlink fail", "<buildstat [^<]*name=.failed_postlink.[^<]*/>"), 
-	LogItem('flmcalls', '<flm'), 
-	LogItem('e32 flmcalls', "<flm +name=[\"']e32abiv2[\"'].* type=[\"'](?!implib)"),
-	#LogItem('mmp_processed', "<parsing[ \t]*file='.*\.[Mm][Mm][Pp]'.*>"),
-	#LogItem('bldinf_processed', "Processing bld.inf:"),
-	LogItem('armar','armar'),
-	LogItem("failed stringtable export", "<buildstat [^<]*name=.failed_exportstringtableheader.[^<]*/>"), 
-	LogItem("failed template extension makefile", "<buildstat [^<]*name=.failed_tem.[^<]*/>"), 
-	LogItem("make error",'^make: \*\*\*.*$', True),
-	LogItem("make no rule",'^make: \*\*\*.* No rule to make target.*$', True),
-	LogItem("raptor error",'^ERROR: raptor:*$', True),
-	LogItem("armcc/armcpp error",'^.*line [0-9]+:.*Error: *#[0-9]+.*$', True),
-	LogItem("gcc/gcc-cpp error",'^[^ \t]+:[0-9]+:[0-9]+ .+:.+$', True),
-	LogItem("armlink error",'^Error: *L[0-9A-F]+:.*$', True),
-	LogItem("Resource File error",'[\t ]*Error:.*cannot open source input file.*\.[Rr][Ss][Gg]\".*$', True),
-	LogItem("String Table error",'[\t ]*Error:.*cannot open source input file.*[Ss]tr[^ ]*\.h\".*$', True),
-	LogItem("Armcc license fail",'^.*Error: C3397E: Cannot obtain license for Compiler.*'),
-	LogItem("Armlink license fail",'^.*Error: ......: Cannot obtain license for .*ink.*')
-	] 
-
-genstats(file,logitems,logdate)
-
-if file != sys.stdin:
-	file.close()
+#
+# 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: 
+# Generate some useful statistics from a Raptor build log
+#
+
+import sys
+from  optparse import OptionParser
+from raptorlog import *
+import os
+from stat import *
+import time
+
+def genstats(file, logitems, logdate):
+	bytecount=0.0
+	lastbytecount=0.0
+	print """<?xml version="1.0" encoding="UTF-8"?>
+       <stats xmlns="http://symbian.com/2007/xml/build/raptor/stats"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xsi:schemaLocation="http://symbian.com/2007/xml/build/raptor/stats http://symbian.com/2007/xml/build/raptor/stats1_0.xsd">
+	"""
+
+	if S_ISREG(os.stat(file.name)[ST_MODE]) > 0:
+	 	totalbytes = os.stat(file.name)[ST_SIZE]+0.0
+	else:
+		totalbytes=0.0
+
+	print "<build log='%s' size='%9.0f' date='%s'>" % (file.name,totalbytes,logdate)
+	for l in file.xreadlines():
+		if totalbytes > 0.0:
+			bytecount += len(l)
+			if (bytecount-lastbytecount)/totalbytes > 0.05:
+				lastbytecount = bytecount
+				sys.stderr.write("%3.0f %%" % ((bytecount/totalbytes)*100.0))
+
+		for i in logitems:
+			i.match(l)
+
+	for i in logitems:
+		print i.xml()+"\n"
+		
+	print "</build>"
+	print "</stats>"
+
+
+
+## Command Line Interface ####################################################
+
+parser = OptionParser(prog = "buildstats",
+	usage = "%prog [-h | options] [<file>]")
+
+parser.add_option("-k", "--keep", default = False,
+	 action="store_true", dest="keep", help="Retain matched log lines and display them.") 
+parser.add_option("-d", "--logdate", default = None,
+	 action="store", dest="logdate", help="Specify the date on which the log was started (yyyymmdd).") 
+
+(options, args) = parser.parse_args()
+
+logname="stdin"
+if len(args) > 0:
+	logname=args[0]
+	file = open(logname,"r")
+	if options.logdate != None:
+		logdate = options.logdate
+	else:
+		logdate = time.strftime("%Y%m%d",time.localtime(os.stat(file.name)[ST_CTIME]))
+else:
+	file = sys.stdin
+	logdate = time.strftime("%Y%m%d")
+
+
+if options.keep != False:
+	LogItem.keep = True
+
+
+
+logitems = [ 
+	LogItem("compile attempt", "<compile.*>"), 
+	LogItem("compile success", "<buildstat [^<]*name='compile'[^<]*/>"), 
+	LogItem("compile fail", "<buildstat [^<]*name='failed_compile'[^<]*/>"), 
+	LogItem('link attempt','<link>'), 
+	LogItem("link success", "<buildstat [^<]*name='link'[^<]*/>"), 
+	LogItem("link fail", "<buildstat [^<]*name=.failed_link.[^<]*/>"), 
+	LogItem('postlink attempt','<postlink.*>'), 
+	LogItem("postlink success", "<buildstat [^<]*name=.postlink[^<]*/>"), 
+	LogItem("postlink fail", "<buildstat [^<]*name=.failed_postlink.[^<]*/>"), 
+	LogItem('flmcalls', '<flm'), 
+	LogItem('e32 flmcalls', "<flm +name=[\"']e32abiv2[\"'].* type=[\"'](?!implib)"),
+	#LogItem('mmp_processed', "<parsing[ \t]*file='.*\.[Mm][Mm][Pp]'.*>"),
+	#LogItem('bldinf_processed', "Processing bld.inf:"),
+	LogItem('armar','armar'),
+	LogItem("failed stringtable export", "<buildstat [^<]*name=.failed_exportstringtableheader.[^<]*/>"), 
+	LogItem("failed template extension makefile", "<buildstat [^<]*name=.failed_tem.[^<]*/>"), 
+	LogItem("make error",'^make: \*\*\*.*$', True),
+	LogItem("make no rule",'^make: \*\*\*.* No rule to make target.*$', True),
+	LogItem("raptor error",'^ERROR: raptor:*$', True),
+	LogItem("armcc/armcpp error",'^.*line [0-9]+:.*Error: *#[0-9]+.*$', True),
+	LogItem("gcc/gcc-cpp error",'^[^ \t]+:[0-9]+:[0-9]+ .+:.+$', True),
+	LogItem("armlink error",'^Error: *L[0-9A-F]+:.*$', True),
+	LogItem("Resource File error",'[\t ]*Error:.*cannot open source input file.*\.[Rr][Ss][Gg]\".*$', True),
+	LogItem("String Table error",'[\t ]*Error:.*cannot open source input file.*[Ss]tr[^ ]*\.h\".*$', True),
+	LogItem("Armcc license fail",'^.*Error: C3397E: Cannot obtain license for Compiler.*'),
+	LogItem("Armlink license fail",'^.*Error: ......: Cannot obtain license for .*ink.*')
+	] 
+
+genstats(file,logitems,logdate)
+
+if file != sys.stdin:
+	file.close()
--- a/sbsv2/raptor/bin/codetest_osbuild.sh	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/codetest_osbuild.sh	Wed Jun 23 16:56:47 2010 +0800
@@ -1,174 +1,174 @@
-#!/bin/sh
-
-# 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:
-# Build automation for Symbian OS with Raptor
-# Author: Timothy N Murphy
-# 
-#
-
-# You can edit these:
-H=/home/tmurphy
-export H
-
-export TESTBASE="$H/baselineos/codetest"
-
-
-export LOGBASEDIR=~/public_html/buildlogs
-export BUILDROOT="$H/baselineos"
-export SOURCEROOT="$H/baselineos/fsupdate"
-export SYSDEF="$H/baselineos/system_definition_fsupdate.xml"
-export PREEXPORTSYSDEF="$SBS_HOME/test/envelope/preexport.xml"
-export PARALLEL=28
-
-genstats() { 
-if [ "$1.stats"  -ot "$1.log" ]; then
-python "$SBS_HOME/bin/buildstats.py"  "$1.log" >  "$1.stats" && 
-#python "$SBS_HOME/bin/failedstats.py" -m  "$1.log" >  "$1.failed"; 
-(
-	cd $EPOCROOT/epoc32 && find "release" > "$1.release_files" && find "build" > "$1.build_files" && find include > "$1.include_files"
-)
-fi;
-}
-
-cd $BUILDROOT
-
-
-# Don't edit the rest:
-###################################################
-export KEY=`date +%d_%m_%y`
-export DAILYDIR="$LOGBASEDIR/$KEY"
-export BUILDNAME="`basename \"$SYSDEF\" | sed 's#\.[^.][^.]*$##'`"
-export LOGNAME="${BUILDNAME}_${KEY}"
-export PLATFORM=armv5
-export TESTLOG="$DAILYDIR/parallel_codetest.log"
-
-for BUILDNUM in {1..50}; do
-	if [ ! -d "$DAILYDIR/$BUILDNUM" ]; then
-		break
-	fi
-	if [ ! -f "$DAILYDIR/$BUILDNUM/${LOGNAME}_$BUILDNUM.log" ]; then
-		break
-	fi
-done
-
-# make the day's directory
-mkdir -p "$DAILYDIR"
-
-echo "testrun: $TESTLOG, build $BUILDNUM of the day:"
-echo '<testrun>' > "$TESTLOG"
-
-
-# Loop through different cluster loads
-for CODEFACTOR in 1 2 3 4 5; do
-export CODEFACTOR
-echo "CODEFACTOR: $CODEFACTOR"
-(
-
-export EPOCROOTS=""
-j=1;
-while [ $j -le $CODEFACTOR ]; do
-	EPOCROOTS=${EPOCROOTS}" $TESTBASE/epocroot$j"
-	j=$[ $j + 1 ]
-done
-MAKEFILE=$TESTBASE/test$CODEFACTOR.mk
-
-
-echo "<test type='performance' name='codetest' >"
-echo "	<parameters codefactor='$CODEFACTOR' start='`date`' />"
-echo "	<logfile>$DAILYDIR/$BUILDNUM/${LOGNAME}_$BUILDNUM.log</logfile>"
-echo "	<epocroots>$EPOCROOTS</epocroots>"
-echo "	<makefile>$MAKEFILE</makefile>"
-echo ""
-
-OUTDIR="$DAILYDIR/$BUILDNUM"
-TIMELOG="$OUTDIR/${LOGNAME}_$BUILDNUM.time"
-
-echo "	<build number='$BUILDNUM' of='$KEY' output='$OUTDIR'><![CDATA["
-if [ ! -d "$OUTDIR" ]; then
-	mkdir -p "$OUTDIR" || exit 1
-fi
-set -x
-
-# Make sure that our "stop signal" is clear
-SIGNALTOSTOPFILE="$OUTDIR/${LOGNAME}_$BUILDNUM.stop"
-rm -f "$SIGNALTOSTOPFILE"
-
-
-export PATH="$TESTBASE/epocroot1/epoc32/tools":$PATH
-
-(
-echo "Annihilating epoc32 tree(s)"
-# wipe the epoc32 directory first
-for e in $EPOCROOTS; do
-	chmod -R u+rw "$e/epoc32" &&
-	rm -rf "$e/epoc32" &&
-	echo "epoc32 tree $e/epoc32 withered" 
-done
-) 
-(
-for EPOCROOT in $EPOCROOTS; do
-	export EPOCROOT
-	# unzip the pre-prepared epoc32 trees
-	cd $EPOCROOT && 	
-	unzip -o $BUILDROOT/epoc32.zip  | grep "epoc32/" | sed 's#.* \(epoc32/.*\)#\1#' | xargs touch && 
-	unzip -o $BUILDROOT/variant.zip  | grep "epoc32/" | sed 's#.* \(epoc32/.*\)#\1#' | xargs touch &&
-	chmod -R u+rw "$EPOCROOT/epoc32" &&
-	echo "unzipped skeleton epoc32 tree" 
-
-	echo "Pre-export"
-	$SBS_HOME/bin/sbs  -d -k -s "$PREEXPORTSYSDEF" -a "$SOURCEROOT" -c $PLATFORM EXPORT > $OUTDIR/${LOGNAME}_$BUILDNUM.preexport 2>&1 || {
-		echo "Pre-export failed";
-		exit 1
-	}
-done
-)
-
-echo "Running Make"
-(
-	set -x
-	echo "Running Make"
-	# The build process
-
-	time /usr/local/raptor/make-pvm-381/pvmgmake -j$PARALLEL --debug=j -k -f $MAKEFILE  > "$OUTDIR/${LOGNAME}_$BUILDNUM.log" 2>&1 
-	touch "$SIGNALTOSTOPFILE"
-) > "$TIMELOG" 2>&1 & 
-(
-	set +x
-	# Concurrent process to continuously update statistics
-	echo ""
-
-	while [ 1 -eq 1 ]; do
-		sleep 20 
-		echo -n "."
-
-		if [ -e "$SIGNALTOSTOPFILE" ]; then
-			rm -f "$SIGNALTOSTOPFILE"
-			break
-		fi
-	done
-	echo ""
-)
-set +x
-genstats "$OUTDIR/${LOGNAME}_$BUILDNUM"
-
-echo "	]]></build>"
-echo "</test>"
-) >> "$TESTLOG" 2>&1
-
-BUILDNUM=$[ $BUILDNUM + 1 ]
-# use a new output directory
-done # CODEFACTOR
-echo -e "<testrun_stat endtime='`date`'\n />" >> "$TESTLOG"
-echo "</testrun>" >> "$TESTLOG"
+#!/bin/sh
+
+# 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:
+# Build automation for Symbian OS with Raptor
+# Author: Timothy N Murphy
+# 
+#
+
+# You can edit these:
+H=/home/tmurphy
+export H
+
+export TESTBASE="$H/baselineos/codetest"
+
+
+export LOGBASEDIR=~/public_html/buildlogs
+export BUILDROOT="$H/baselineos"
+export SOURCEROOT="$H/baselineos/fsupdate"
+export SYSDEF="$H/baselineos/system_definition_fsupdate.xml"
+export PREEXPORTSYSDEF="$SBS_HOME/test/envelope/preexport.xml"
+export PARALLEL=28
+
+genstats() { 
+if [ "$1.stats"  -ot "$1.log" ]; then
+python "$SBS_HOME/bin/buildstats.py"  "$1.log" >  "$1.stats" && 
+#python "$SBS_HOME/bin/failedstats.py" -m  "$1.log" >  "$1.failed"; 
+(
+	cd $EPOCROOT/epoc32 && find "release" > "$1.release_files" && find "build" > "$1.build_files" && find include > "$1.include_files"
+)
+fi;
+}
+
+cd $BUILDROOT
+
+
+# Don't edit the rest:
+###################################################
+export KEY=`date +%d_%m_%y`
+export DAILYDIR="$LOGBASEDIR/$KEY"
+export BUILDNAME="`basename \"$SYSDEF\" | sed 's#\.[^.][^.]*$##'`"
+export LOGNAME="${BUILDNAME}_${KEY}"
+export PLATFORM=armv5
+export TESTLOG="$DAILYDIR/parallel_codetest.log"
+
+for BUILDNUM in {1..50}; do
+	if [ ! -d "$DAILYDIR/$BUILDNUM" ]; then
+		break
+	fi
+	if [ ! -f "$DAILYDIR/$BUILDNUM/${LOGNAME}_$BUILDNUM.log" ]; then
+		break
+	fi
+done
+
+# make the day's directory
+mkdir -p "$DAILYDIR"
+
+echo "testrun: $TESTLOG, build $BUILDNUM of the day:"
+echo '<testrun>' > "$TESTLOG"
+
+
+# Loop through different cluster loads
+for CODEFACTOR in 1 2 3 4 5; do
+export CODEFACTOR
+echo "CODEFACTOR: $CODEFACTOR"
+(
+
+export EPOCROOTS=""
+j=1;
+while [ $j -le $CODEFACTOR ]; do
+	EPOCROOTS=${EPOCROOTS}" $TESTBASE/epocroot$j"
+	j=$[ $j + 1 ]
+done
+MAKEFILE=$TESTBASE/test$CODEFACTOR.mk
+
+
+echo "<test type='performance' name='codetest' >"
+echo "	<parameters codefactor='$CODEFACTOR' start='`date`' />"
+echo "	<logfile>$DAILYDIR/$BUILDNUM/${LOGNAME}_$BUILDNUM.log</logfile>"
+echo "	<epocroots>$EPOCROOTS</epocroots>"
+echo "	<makefile>$MAKEFILE</makefile>"
+echo ""
+
+OUTDIR="$DAILYDIR/$BUILDNUM"
+TIMELOG="$OUTDIR/${LOGNAME}_$BUILDNUM.time"
+
+echo "	<build number='$BUILDNUM' of='$KEY' output='$OUTDIR'><![CDATA["
+if [ ! -d "$OUTDIR" ]; then
+	mkdir -p "$OUTDIR" || exit 1
+fi
+set -x
+
+# Make sure that our "stop signal" is clear
+SIGNALTOSTOPFILE="$OUTDIR/${LOGNAME}_$BUILDNUM.stop"
+rm -f "$SIGNALTOSTOPFILE"
+
+
+export PATH="$TESTBASE/epocroot1/epoc32/tools":$PATH
+
+(
+echo "Annihilating epoc32 tree(s)"
+# wipe the epoc32 directory first
+for e in $EPOCROOTS; do
+	chmod -R u+rw "$e/epoc32" &&
+	rm -rf "$e/epoc32" &&
+	echo "epoc32 tree $e/epoc32 withered" 
+done
+) 
+(
+for EPOCROOT in $EPOCROOTS; do
+	export EPOCROOT
+	# unzip the pre-prepared epoc32 trees
+	cd $EPOCROOT && 	
+	unzip -o $BUILDROOT/epoc32.zip  | grep "epoc32/" | sed 's#.* \(epoc32/.*\)#\1#' | xargs touch && 
+	unzip -o $BUILDROOT/variant.zip  | grep "epoc32/" | sed 's#.* \(epoc32/.*\)#\1#' | xargs touch &&
+	chmod -R u+rw "$EPOCROOT/epoc32" &&
+	echo "unzipped skeleton epoc32 tree" 
+
+	echo "Pre-export"
+	$SBS_HOME/bin/sbs  -d -k -s "$PREEXPORTSYSDEF" -a "$SOURCEROOT" -c $PLATFORM EXPORT > $OUTDIR/${LOGNAME}_$BUILDNUM.preexport 2>&1 || {
+		echo "Pre-export failed";
+		exit 1
+	}
+done
+)
+
+echo "Running Make"
+(
+	set -x
+	echo "Running Make"
+	# The build process
+
+	time /usr/local/raptor/make-pvm-381/pvmgmake -j$PARALLEL --debug=j -k -f $MAKEFILE  > "$OUTDIR/${LOGNAME}_$BUILDNUM.log" 2>&1 
+	touch "$SIGNALTOSTOPFILE"
+) > "$TIMELOG" 2>&1 & 
+(
+	set +x
+	# Concurrent process to continuously update statistics
+	echo ""
+
+	while [ 1 -eq 1 ]; do
+		sleep 20 
+		echo -n "."
+
+		if [ -e "$SIGNALTOSTOPFILE" ]; then
+			rm -f "$SIGNALTOSTOPFILE"
+			break
+		fi
+	done
+	echo ""
+)
+set +x
+genstats "$OUTDIR/${LOGNAME}_$BUILDNUM"
+
+echo "	]]></build>"
+echo "</test>"
+) >> "$TESTLOG" 2>&1
+
+BUILDNUM=$[ $BUILDNUM + 1 ]
+# use a new output directory
+done # CODEFACTOR
+echo -e "<testrun_stat endtime='`date`'\n />" >> "$TESTLOG"
+echo "</testrun>" >> "$TESTLOG"
--- a/sbsv2/raptor/bin/countbinaries.sh	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/countbinaries.sh	Wed Jun 23 16:56:47 2010 +0800
@@ -1,29 +1,29 @@
-#!/bin/sh
-# 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:
-# Count the release binaries produced by a build
-# armv5 only for the moment
-#
-
-TYPES='agt ani cpm csy dll drv esy exe fsy fxt hlp jar ldd lib loc msy nif pdd pdl prt sc tsy wsy [0-9]+'
-
-echo "Countbinaries"
-echo  ""
-
-PATTERN='\.(('`echo "$TYPES" |sed 's# #)|(#g'`'))$'
-echo "Searching for: $PATTERN"
-
-
-echo -n "ARMv5 Binaries: "
-find $EPOCROOT/epoc32/release/armv5 | egrep "$PATTERN" | wc
+#!/bin/sh
+# 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:
+# Count the release binaries produced by a build
+# armv5 only for the moment
+#
+
+TYPES='agt ani cpm csy dll drv esy exe fsy fxt hlp jar ldd lib loc msy nif pdd pdl prt sc tsy wsy [0-9]+'
+
+echo "Countbinaries"
+echo  ""
+
+PATTERN='\.(('`echo "$TYPES" |sed 's# #)|(#g'`'))$'
+echo "Searching for: $PATTERN"
+
+
+echo -n "ARMv5 Binaries: "
+find $EPOCROOT/epoc32/release/armv5 | egrep "$PATTERN" | wc
--- a/sbsv2/raptor/bin/createrfifile.pl	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/createrfifile.pl	Wed Jun 23 16:56:47 2010 +0800
@@ -1,114 +1,114 @@
-#
-# 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: 
-#
-
-use strict;
-use File::Basename;
-use Getopt::Long;
-
-my $verbose = 0;
-my ($rfifile, $excludepath) = "";
-GetOptions ('v' => \$verbose, 'o=s' => \$rfifile, 'x=s' => \$excludepath);
-
-if (!$rfifile || @ARGV < 1)
-	{
-	print (STDERR "\ncreaterfifile.pl\n");
-	print STDERR << 'END_OF_HELP';
-
-Usage: createrfifile.pl [-v] -o outputfile.rfi [-x excludepath] rss_cpp_deps_file_1.d rss_cpp_deps_file_n.d
-
-Takes one or more files containing CPP dependency output from the preprocessing of a .rss file and
-generates a "combined resource" .rfi that can  be consumed by CDB.
-Optionally takes an exclusion path under which "found" dependencies can be ignored.
-
-END_OF_HELP
-	exit(0);
-	}
-
-my @depfiles = @ARGV;
-
-my $exclude = $excludepath;
-if ($exclude)
-	{
-	$exclude =~ s/\\/\//g;			# Ensure consistent slashes
-	$exclude =~ s/\/\//\//g;		# Remove double slashes
-	$exclude = quotemeta($exclude);	# Convert for regex match
-	}
-
-print ("RFI : exclude under - \"$exclude\"\n") if ($verbose);
-
-my @resources;
-my %loggedresources;
-foreach my $depfile (@depfiles)
-	{
-	open DEPFILE, "< $depfile" or die "\nRFI : Cannot read \"$depfile\"!\n\n";
-	while (<DEPFILE>)
-		{
-		# .d file format - whitespace at front is key, path format varies depending on platform
-		# the aim is to get a list of the "real" files. Missing files can appear "unpathed"
-		#
-		#Audio.rsc: M:/src/common/techview/apps/audio/Src/Audio.rss \
-		#  M:/epoc32/include/variant/Symbian_OS.hrh \
-		#  M://epoc32/include/techview/eikon.rh \
-		#  M://epoc32/include/techview/eikon.hrh M://epoc32/include/uikon.hrh \
-		#  M://epoc32/include/techview/controls.hrh \
-		#  M://epoc32/include/eikcolor.hrh \
-		#  M://epoc32/include/techview/techview.hrh M://epoc32/include/uikon.rh \
-		#  M://epoc32/include/badef.rh M://epoc32/include/baerrrsvr.rh \
-		#  M://epoc32/include/techview/controls.rh M://epoc32/include/gulftflg.hrh \
-		#  M://epoc32/include/eikcore.rsg M://epoc32/include/eikcoctl.rsg \
-		#  M://epoc32/include/eikctl.rsg M://epoc32/include/eikfile.rsg \
-		#  M://epoc32/include/eikprint.rsg M://epoc32/include/audio.mbg \
-		#  M:/src/common/techview/apps/audio/Src/Audio.hrh \
-		#  M:/src/common/techview/apps/audio/Src/NewAudio.rls
-		
-		s/^.*\.\w+\://;
-		s/\\$//;
-		s/^\s+//;
-		s/\s+$//;
-		s/\/\//\//g;
-		chomp $_;
-		next if !/\S/;	
-	
-		my @dependencies = split;	
-		foreach my $dependency (@dependencies)
-			{
-			next if ($exclude && $dependency =~ /^$exclude/i);
-			print ("WARNING: Could not find dependency \"$dependency\" in \"$depfile\"\n") if (!-e $dependency and $verbose);		
-			print ("RFI : processing - \"$dependency\"\n") if ($verbose);
-			
-			if (!defined $loggedresources{$dependency})
-				{
-				push @resources, $dependency;
-				$loggedresources{$dependency} = 1;
-				}
-			}
-		}
-	close DEPFILE;
-	}
-
-open RFIFILE, "> $rfifile" or die "\nRFI : Cannot write \"$rfifile\"!\n\n";
-foreach my $resource (@resources)
-	{
-	print RFIFILE "\n\n/* GXP ***********************\n";
-	print RFIFILE " * ".basename($resource)."\n";
-	print RFIFILE " ****************************/\n\n";
-	
-	open RESOURCE, "< $resource" or die "\nCannot read \"$resource\"!\n\n";
-	print RFIFILE $_ while (<RESOURCE>);
-	close RESOURCE;
-	}
-close RFIFILE;
-
+#
+# 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: 
+#
+
+use strict;
+use File::Basename;
+use Getopt::Long;
+
+my $verbose = 0;
+my ($rfifile, $excludepath) = "";
+GetOptions ('v' => \$verbose, 'o=s' => \$rfifile, 'x=s' => \$excludepath);
+
+if (!$rfifile || @ARGV < 1)
+	{
+	print (STDERR "\ncreaterfifile.pl\n");
+	print STDERR << 'END_OF_HELP';
+
+Usage: createrfifile.pl [-v] -o outputfile.rfi [-x excludepath] rss_cpp_deps_file_1.d rss_cpp_deps_file_n.d
+
+Takes one or more files containing CPP dependency output from the preprocessing of a .rss file and
+generates a "combined resource" .rfi that can  be consumed by CDB.
+Optionally takes an exclusion path under which "found" dependencies can be ignored.
+
+END_OF_HELP
+	exit(0);
+	}
+
+my @depfiles = @ARGV;
+
+my $exclude = $excludepath;
+if ($exclude)
+	{
+	$exclude =~ s/\\/\//g;			# Ensure consistent slashes
+	$exclude =~ s/\/\//\//g;		# Remove double slashes
+	$exclude = quotemeta($exclude);	# Convert for regex match
+	}
+
+print ("RFI : exclude under - \"$exclude\"\n") if ($verbose);
+
+my @resources;
+my %loggedresources;
+foreach my $depfile (@depfiles)
+	{
+	open DEPFILE, "< $depfile" or die "\nRFI : Cannot read \"$depfile\"!\n\n";
+	while (<DEPFILE>)
+		{
+		# .d file format - whitespace at front is key, path format varies depending on platform
+		# the aim is to get a list of the "real" files. Missing files can appear "unpathed"
+		#
+		#Audio.rsc: M:/src/common/techview/apps/audio/Src/Audio.rss \
+		#  M:/epoc32/include/variant/Symbian_OS.hrh \
+		#  M://epoc32/include/techview/eikon.rh \
+		#  M://epoc32/include/techview/eikon.hrh M://epoc32/include/uikon.hrh \
+		#  M://epoc32/include/techview/controls.hrh \
+		#  M://epoc32/include/eikcolor.hrh \
+		#  M://epoc32/include/techview/techview.hrh M://epoc32/include/uikon.rh \
+		#  M://epoc32/include/badef.rh M://epoc32/include/baerrrsvr.rh \
+		#  M://epoc32/include/techview/controls.rh M://epoc32/include/gulftflg.hrh \
+		#  M://epoc32/include/eikcore.rsg M://epoc32/include/eikcoctl.rsg \
+		#  M://epoc32/include/eikctl.rsg M://epoc32/include/eikfile.rsg \
+		#  M://epoc32/include/eikprint.rsg M://epoc32/include/audio.mbg \
+		#  M:/src/common/techview/apps/audio/Src/Audio.hrh \
+		#  M:/src/common/techview/apps/audio/Src/NewAudio.rls
+		
+		s/^.*\.\w+\://;
+		s/\\$//;
+		s/^\s+//;
+		s/\s+$//;
+		s/\/\//\//g;
+		chomp $_;
+		next if !/\S/;	
+	
+		my @dependencies = split;	
+		foreach my $dependency (@dependencies)
+			{
+			next if ($exclude && $dependency =~ /^$exclude/i);
+			print ("WARNING: Could not find dependency \"$dependency\" in \"$depfile\"\n") if (!-e $dependency and $verbose);		
+			print ("RFI : processing - \"$dependency\"\n") if ($verbose);
+			
+			if (!defined $loggedresources{$dependency})
+				{
+				push @resources, $dependency;
+				$loggedresources{$dependency} = 1;
+				}
+			}
+		}
+	close DEPFILE;
+	}
+
+open RFIFILE, "> $rfifile" or die "\nRFI : Cannot write \"$rfifile\"!\n\n";
+foreach my $resource (@resources)
+	{
+	print RFIFILE "\n\n/* GXP ***********************\n";
+	print RFIFILE " * ".basename($resource)."\n";
+	print RFIFILE " ****************************/\n\n";
+	
+	open RESOURCE, "< $resource" or die "\nCannot read \"$resource\"!\n\n";
+	print RFIFILE $_ while (<RESOURCE>);
+	close RESOURCE;
+	}
+close RFIFILE;
+
--- a/sbsv2/raptor/bin/createvmap.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/createvmap.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,310 +1,310 @@
-#
-# 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: 
-#
-
-# Python Script to create the vmap file for Binary Variation support in SBSv2
-
-import sys
-import os
-import re
-import subprocess
-import tempfile
-import traceback
-from optparse import OptionParser
-
-# the script will exit with 0 if there are no errors
-global exitCode
-exitCode = 0
-
-# are we running on Windows?
-onWindows = sys.platform.lower().startswith("win")
-
-# error messages go to stderr
-def error(format, *extras):
-	sys.stderr.write("createvmap: error: " + (format % extras) + "\n")
-	global exitCode
-	exitCode = 1
-
-# warning messages go to stderr
-def warning(format, *extras):
-	sys.stderr.write("createvmap: warning: " + (format % extras) + "\n")
-
-# debug messages go to stderr
-global printDebug
-#
-def debug(format, *extras):
-	if printDebug:
-		sys.stderr.write("createvmap: " + (format % extras) + "\n")
-	
-# Return a dictionary with the feature names and values from the preinclude file, by running cpp over the source
-def getVmapMacros(aPreInclude, aPreprocessedFile=None, aCPP="cpp", aDefines="", aIncludes = ""):
-
-	validmacros = {}
-	# Run the pre-processor
-	command = aCPP + " -include " + os.path.abspath(aPreInclude) + " -dU " + aDefines + aIncludes
-
-	# Feed in the file to stdin, because we must set the stdin to something
-	# other than the parent stdin anyway as that may not exist - for example
-	# when using Talon.
-	infile = open(aPreprocessedFile, "r")
-
-	if onWindows:
-		p = subprocess.Popen(command, bufsize=65535,
-					                  stdin=infile,
-					                  stdout=subprocess.PIPE,
-					                  stderr=sys.stderr,
-					                  universal_newlines=True)
-	else:
-		p = subprocess.Popen(command, bufsize=65535,
-					                  stdin=infile,
-					                  stdout=subprocess.PIPE,
-					                  stderr=sys.stderr,
-					                  close_fds=True, shell=True)
-	stream = p.stdout
-
-	# Parse the pre-processor output to look for -
-	# lines "#define NAME VALUE" and "#undef NAME"
-	defineRE = re.compile('^#define (?P<FEATURENAME>\w+)(\s+(?P<VALUE>\w+))?')
-	undefRE = re.compile('^#undef (?P<FEATURENAME>\w+)')
-
-	data = " "
-	while data:
-		data = stream.readline()
-
-		definedmacro = defineRE.match(data)
-		if definedmacro:
-			name = definedmacro.group('FEATURENAME')
-			value = definedmacro.group('VALUE')
-			if value:
-				validmacros[name] = value
-			else:
-				validmacros[name] = "defined"
-
-		else:
-			undefinedmacro = undefRE.match(data)
-			if undefinedmacro:
-				validmacros[undefinedmacro.group('FEATURENAME')] = "undefined"
-
-	if p.wait() != 0:
-		error("in command '%s'", command)
-		
-	infile.close()
-	
-	return validmacros
-
-# Extract the features from a featurelist file
-def getFeatures(aFeatureList):
-	features = set()
-	for f in aFeatureList:
-		try:
-			file = open(os.path.abspath(f),'r')
-		
-			for data in file.readlines():
-				data = data.strip()
-				features.add(data)
-		
-			file.close()
-		
-		except IOError:
-			error("Feature list file %s not found", f)
-
-	return sorted(list(features))
-	
-# Returns a dictionary of the features to be put in the vmap file
-def getVariationFeatures(aFeatureList = [] ,aPreinclude = None,aPreprocessedFile = None,aCPP = "cpp",aDefines="",aIncludes = ""):
-	
-	variation_features = {'FEATURENAME':[],'VALUE':[]}
-	macros = getVmapMacros(aPreinclude,aPreprocessedFile,aCPP,aDefines,aIncludes)
-	
-	# Co-relate the macros obtained from the pre-processor to the featurelist
-	for f in aFeatureList:
-		if f in macros:
-			variation_features['FEATURENAME'].append(f)
-			variation_features['VALUE'].append(macros[f])
-	
-	return variation_features
-
-# Write to the vmap file, with the supplied dictionary containing the features
-# The vmap path will be created if it doesn't exist
-def createVmapFile(aMacroDictionary,aOutputfile):
-	if not os.path.exists(os.path.dirname(aOutputfile)):
-		os.makedirs(os.path.dirname(aOutputfile))
-	try:
-		vmapfile = open(aOutputfile,'w')
-	except IOError:
-		error("Cannot write to " + aOutputfile)
-	i = 0
-	while i < len(aMacroDictionary['FEATURENAME']):
-		vmapfile.write(aMacroDictionary['FEATURENAME'][i]+"="+aMacroDictionary['VALUE'][i]+"\n")
-		i += 1
-	vmapfile.close()
-
-def check_exists(thing, filenames):
-	if not filenames:
-		error("No %s specified", thing)
-		return
-	
-	if not isinstance(filenames, list):
-		# we just have a single string
-		filenames = [filenames]
-		
-	for filename in filenames:
-		if not os.path.exists(filename):
-			error("The %s '%s' does not exist", thing, filename)
-		
-# Main function, creates the vmap file
-def main():
-
-	try:
-		global exitCode, printDebug
-		
-		# any exceptions make us traceback and exit
-
-		parser = OptionParser(prog = "createvmap.py")
-	
-		parser.add_option("-c","--cpploc",action="store",dest="cpplocation",help="Full path of the preprocessor")
-		parser.add_option("-d","--debug",action="store_true",default=False,dest="debug",help="Turn debug information on")
-		parser.add_option("-D","--define",action="append",dest="defines",help="Macro definition")
-		parser.add_option("-f","--featurelist",action="append",dest="featurelistfile",help="List of featureslist files")
-		parser.add_option("-o","--output",action="store",dest="outputvmapfile",help="Output VMAP file name")
-		parser.add_option("-p","--preinclude",action="store",dest="preinclude",help="Pre-include file ")
-		parser.add_option("-s","--source",action="append",dest="sourcefiles",help="List of source files")
-		parser.add_option("-u","--userinc",action="append",dest="user_include",help="User Include Folders")
-		parser.add_option("-x","--systeminc",action="append",dest="system_include",help="System Include Folders")
-
-		(options, leftover_args) = parser.parse_args(sys.argv[1:])
-
-		if leftover_args:
-			for invalids in leftover_args:
-				warning("Unknown parameter '%s'" % invalids)
-		
-		printDebug = options.debug
-		debug("Source Files     -> %s", options.sourcefiles)
-		debug("Macro defines    -> %s", options.defines)
-		debug("Features Files   -> %s", options.featurelistfile)
-		debug("Pre-Include File -> %s", options.preinclude)
-		debug("User Includes    -> %s", options.user_include)
-		debug("System Includes  -> %s", options.system_include)
-		debug("CPP Location     -> %s", options.cpplocation)
-		debug("VMAP Output name -> %s", options.outputvmapfile)
-			
-		featurelist = []
-		definelist = ""
-		user_includeslist = ""
-		system_includeslist = ""
-		includeslist = ""
-
-		# Some error checking code
-		if not options.outputvmapfile:
-			error("No output vmap file name supplied")
-	
-		# Source files must be supplied
-		check_exists("source file", options.sourcefiles)
-	
-		# A valid preinclude file must be supplied
-		check_exists("pre-include file", options.preinclude)
-	
-		# Some feature lists are required
-		check_exists("feature list", options.featurelistfile)
-	
-		# A cpp tool is required
-		check_exists("cpp tool", options.cpplocation)
-
-		# if an essential option was missing then we should stop now
-		if exitCode != 0:
-			sys.exit(exitCode)
-			
-		# macro definitions
-		if options.defines:
-			for macro in options.defines:
-				definelist += " -D" + macro.replace('__SBS__QUOTE__', '\\"')
-
-		# Note that we have to use -isystem for user includes and system
-		# includes to match what happens in the compiler. Long story.
-
-		# Add each source directory as a user-include, so that our temporary
-		# concatenated source file can find includes that were next to the
-		# original source files.
-		# Check that all the specified source files exist
-		# and collect a set of all the source directories
-		sourcedirs = set()
-		for src in options.sourcefiles:
-			sourcedirs.add(os.path.dirname(src))
-			
-		for srcdir in sourcedirs:
-			user_includeslist += " -isystem " + srcdir
-
-		# Convert the include list to a string to be passed to cpp
-		if options.user_include:
-			for userinc in options.user_include:
-				user_includeslist += " -isystem " + userinc
-		if options.system_include:
-			for sysinc in options.system_include:
-				system_includeslist += " -isystem " + sysinc
-	
-		includeslist = user_includeslist + system_includeslist
-
-		# Get a list of all the features, from all the featurelist files
-		featurelist = getFeatures(options.featurelistfile)
-
-		# concatenate the source files together into a temporary file
-		try:
-			(tempfd, tempname) = tempfile.mkstemp()
-			temp = os.fdopen(tempfd, "w")
-			for src in options.sourcefiles:
-				sfile = open(src, "r")
-				for sline in sfile:
-					temp.write(sline)
-				sfile.close()
-			temp.close()
-		except Exception,e:
-			error("Could not write source files into temporary file %s : %s" % (tempname, str(e)))
-			return 1
-		
-		debug("Temporary file name : " + tempname)
-
-		# extract the macros from the concatenated source files
-		macro_dictionary = getVariationFeatures(featurelist,
-		                                        options.preinclude,
-								                tempname,
-								                options.cpplocation,
-								                definelist,
-								                includeslist)
-		debug("Macros extracted:") 
-		for key,values in macro_dictionary.iteritems():
-			debug(key + " " + str(values))
-
-		# if there were no macros then the vmap file will be empty...
-		if not macro_dictionary['FEATURENAME']:
-			warning("No feature macros were found in the source")
-			
-		# Get rid of the temporary file
-		try:
-			os.remove(tempname)
-		except:
-			error("Could not delete temporary %s" % tempname) 
-
-		createVmapFile(macro_dictionary, options.outputvmapfile)
-		
-		# exit with 0 if OK
-		return exitCode
-
-	except Exception,ex:
-		traceback.print_exc()
-		return 1
-
-if __name__ == "__main__":
-    sys.exit(main())
-
+#
+# 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: 
+#
+
+# Python Script to create the vmap file for Binary Variation support in SBSv2
+
+import sys
+import os
+import re
+import subprocess
+import tempfile
+import traceback
+from optparse import OptionParser
+
+# the script will exit with 0 if there are no errors
+global exitCode
+exitCode = 0
+
+# are we running on Windows?
+onWindows = sys.platform.lower().startswith("win")
+
+# error messages go to stderr
+def error(format, *extras):
+	sys.stderr.write("createvmap: error: " + (format % extras) + "\n")
+	global exitCode
+	exitCode = 1
+
+# warning messages go to stderr
+def warning(format, *extras):
+	sys.stderr.write("createvmap: warning: " + (format % extras) + "\n")
+
+# debug messages go to stderr
+global printDebug
+#
+def debug(format, *extras):
+	if printDebug:
+		sys.stderr.write("createvmap: " + (format % extras) + "\n")
+	
+# Return a dictionary with the feature names and values from the preinclude file, by running cpp over the source
+def getVmapMacros(aPreInclude, aPreprocessedFile=None, aCPP="cpp", aDefines="", aIncludes = ""):
+
+	validmacros = {}
+	# Run the pre-processor
+	command = aCPP + " -include " + os.path.abspath(aPreInclude) + " -dU " + aDefines + aIncludes
+
+	# Feed in the file to stdin, because we must set the stdin to something
+	# other than the parent stdin anyway as that may not exist - for example
+	# when using Talon.
+	infile = open(aPreprocessedFile, "r")
+
+	if onWindows:
+		p = subprocess.Popen(command, bufsize=65535,
+					                  stdin=infile,
+					                  stdout=subprocess.PIPE,
+					                  stderr=sys.stderr,
+					                  universal_newlines=True)
+	else:
+		p = subprocess.Popen(command, bufsize=65535,
+					                  stdin=infile,
+					                  stdout=subprocess.PIPE,
+					                  stderr=sys.stderr,
+					                  close_fds=True, shell=True)
+	stream = p.stdout
+
+	# Parse the pre-processor output to look for -
+	# lines "#define NAME VALUE" and "#undef NAME"
+	defineRE = re.compile('^#define (?P<FEATURENAME>\w+)(\s+(?P<VALUE>\w+))?')
+	undefRE = re.compile('^#undef (?P<FEATURENAME>\w+)')
+
+	data = " "
+	while data:
+		data = stream.readline()
+
+		definedmacro = defineRE.match(data)
+		if definedmacro:
+			name = definedmacro.group('FEATURENAME')
+			value = definedmacro.group('VALUE')
+			if value:
+				validmacros[name] = value
+			else:
+				validmacros[name] = "defined"
+
+		else:
+			undefinedmacro = undefRE.match(data)
+			if undefinedmacro:
+				validmacros[undefinedmacro.group('FEATURENAME')] = "undefined"
+
+	if p.wait() != 0:
+		error("in command '%s'", command)
+		
+	infile.close()
+	
+	return validmacros
+
+# Extract the features from a featurelist file
+def getFeatures(aFeatureList):
+	features = set()
+	for f in aFeatureList:
+		try:
+			file = open(os.path.abspath(f),'r')
+		
+			for data in file.readlines():
+				data = data.strip()
+				features.add(data)
+		
+			file.close()
+		
+		except IOError:
+			error("Feature list file %s not found", f)
+
+	return sorted(list(features))
+	
+# Returns a dictionary of the features to be put in the vmap file
+def getVariationFeatures(aFeatureList = [] ,aPreinclude = None,aPreprocessedFile = None,aCPP = "cpp",aDefines="",aIncludes = ""):
+	
+	variation_features = {'FEATURENAME':[],'VALUE':[]}
+	macros = getVmapMacros(aPreinclude,aPreprocessedFile,aCPP,aDefines,aIncludes)
+	
+	# Co-relate the macros obtained from the pre-processor to the featurelist
+	for f in aFeatureList:
+		if f in macros:
+			variation_features['FEATURENAME'].append(f)
+			variation_features['VALUE'].append(macros[f])
+	
+	return variation_features
+
+# Write to the vmap file, with the supplied dictionary containing the features
+# The vmap path will be created if it doesn't exist
+def createVmapFile(aMacroDictionary,aOutputfile):
+	if not os.path.exists(os.path.dirname(aOutputfile)):
+		os.makedirs(os.path.dirname(aOutputfile))
+	try:
+		vmapfile = open(aOutputfile,'w')
+	except IOError:
+		error("Cannot write to " + aOutputfile)
+	i = 0
+	while i < len(aMacroDictionary['FEATURENAME']):
+		vmapfile.write(aMacroDictionary['FEATURENAME'][i]+"="+aMacroDictionary['VALUE'][i]+"\n")
+		i += 1
+	vmapfile.close()
+
+def check_exists(thing, filenames):
+	if not filenames:
+		error("No %s specified", thing)
+		return
+	
+	if not isinstance(filenames, list):
+		# we just have a single string
+		filenames = [filenames]
+		
+	for filename in filenames:
+		if not os.path.exists(filename):
+			error("The %s '%s' does not exist", thing, filename)
+		
+# Main function, creates the vmap file
+def main():
+
+	try:
+		global exitCode, printDebug
+		
+		# any exceptions make us traceback and exit
+
+		parser = OptionParser(prog = "createvmap.py")
+	
+		parser.add_option("-c","--cpploc",action="store",dest="cpplocation",help="Full path of the preprocessor")
+		parser.add_option("-d","--debug",action="store_true",default=False,dest="debug",help="Turn debug information on")
+		parser.add_option("-D","--define",action="append",dest="defines",help="Macro definition")
+		parser.add_option("-f","--featurelist",action="append",dest="featurelistfile",help="List of featureslist files")
+		parser.add_option("-o","--output",action="store",dest="outputvmapfile",help="Output VMAP file name")
+		parser.add_option("-p","--preinclude",action="store",dest="preinclude",help="Pre-include file ")
+		parser.add_option("-s","--source",action="append",dest="sourcefiles",help="List of source files")
+		parser.add_option("-u","--userinc",action="append",dest="user_include",help="User Include Folders")
+		parser.add_option("-x","--systeminc",action="append",dest="system_include",help="System Include Folders")
+
+		(options, leftover_args) = parser.parse_args(sys.argv[1:])
+
+		if leftover_args:
+			for invalids in leftover_args:
+				warning("Unknown parameter '%s'" % invalids)
+		
+		printDebug = options.debug
+		debug("Source Files     -> %s", options.sourcefiles)
+		debug("Macro defines    -> %s", options.defines)
+		debug("Features Files   -> %s", options.featurelistfile)
+		debug("Pre-Include File -> %s", options.preinclude)
+		debug("User Includes    -> %s", options.user_include)
+		debug("System Includes  -> %s", options.system_include)
+		debug("CPP Location     -> %s", options.cpplocation)
+		debug("VMAP Output name -> %s", options.outputvmapfile)
+			
+		featurelist = []
+		definelist = ""
+		user_includeslist = ""
+		system_includeslist = ""
+		includeslist = ""
+
+		# Some error checking code
+		if not options.outputvmapfile:
+			error("No output vmap file name supplied")
+	
+		# Source files must be supplied
+		check_exists("source file", options.sourcefiles)
+	
+		# A valid preinclude file must be supplied
+		check_exists("pre-include file", options.preinclude)
+	
+		# Some feature lists are required
+		check_exists("feature list", options.featurelistfile)
+	
+		# A cpp tool is required
+		check_exists("cpp tool", options.cpplocation)
+
+		# if an essential option was missing then we should stop now
+		if exitCode != 0:
+			sys.exit(exitCode)
+			
+		# macro definitions
+		if options.defines:
+			for macro in options.defines:
+				definelist += " -D" + macro.replace('__SBS__QUOTE__', '\\"')
+
+		# Note that we have to use -isystem for user includes and system
+		# includes to match what happens in the compiler. Long story.
+
+		# Add each source directory as a user-include, so that our temporary
+		# concatenated source file can find includes that were next to the
+		# original source files.
+		# Check that all the specified source files exist
+		# and collect a set of all the source directories
+		sourcedirs = set()
+		for src in options.sourcefiles:
+			sourcedirs.add(os.path.dirname(src))
+			
+		for srcdir in sourcedirs:
+			user_includeslist += " -isystem " + srcdir
+
+		# Convert the include list to a string to be passed to cpp
+		if options.user_include:
+			for userinc in options.user_include:
+				user_includeslist += " -isystem " + userinc
+		if options.system_include:
+			for sysinc in options.system_include:
+				system_includeslist += " -isystem " + sysinc
+	
+		includeslist = user_includeslist + system_includeslist
+
+		# Get a list of all the features, from all the featurelist files
+		featurelist = getFeatures(options.featurelistfile)
+
+		# concatenate the source files together into a temporary file
+		try:
+			(tempfd, tempname) = tempfile.mkstemp()
+			temp = os.fdopen(tempfd, "w")
+			for src in options.sourcefiles:
+				sfile = open(src, "r")
+				for sline in sfile:
+					temp.write(sline)
+				sfile.close()
+			temp.close()
+		except Exception,e:
+			error("Could not write source files into temporary file %s : %s" % (tempname, str(e)))
+			return 1
+		
+		debug("Temporary file name : " + tempname)
+
+		# extract the macros from the concatenated source files
+		macro_dictionary = getVariationFeatures(featurelist,
+		                                        options.preinclude,
+								                tempname,
+								                options.cpplocation,
+								                definelist,
+								                includeslist)
+		debug("Macros extracted:") 
+		for key,values in macro_dictionary.iteritems():
+			debug(key + " " + str(values))
+
+		# if there were no macros then the vmap file will be empty...
+		if not macro_dictionary['FEATURENAME']:
+			warning("No feature macros were found in the source")
+			
+		# Get rid of the temporary file
+		try:
+			os.remove(tempname)
+		except:
+			error("Could not delete temporary %s" % tempname) 
+
+		createVmapFile(macro_dictionary, options.outputvmapfile)
+		
+		# exit with 0 if OK
+		return exitCode
+
+	except Exception,ex:
+		traceback.print_exc()
+		return 1
+
+if __name__ == "__main__":
+    sys.exit(main())
+
--- a/sbsv2/raptor/bin/failedstats.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/failedstats.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,161 +1,161 @@
-#
-# 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: 
-# Generate some useful statistics from a Raptor build log
-# Work out what was specified to make but not built even if
-# it was not mentioned in the make error output because some
-# child's dependency was not satisfied.
-# Needs raptor --tracking option to set make to use -debug=v
-# An example bit of make output that can be analysed:
-#
-
- File `fred.exe' does not exist.
-  Considering target file `fred.in'.
-   File `fred.in' does not exist.
-    Considering target file `a.o'.
-     File `a.o' does not exist.
-      Considering target file `a.c'.
-       Finished prerequisites of target file `a.c'.
-      No need to remake target `a.c'.
-      Pruning file `a.c'.
-     Finished prerequisites of target file `a.o'.
-    Must remake target `a.o'.
-cc    -c -o a.o a.c
-    Successfully remade target file `a.o'.
-    Considering target file `b.o'.
-     File `b.o' does not exist.
-      Considering target file `b.c'.
-       Finished prerequisites of target file `b.c'.
-      No need to remake target `b.c'.
-      Pruning file `b.c'.
-     Finished prerequisites of target file `b.o'.
-    Must remake target `b.o'.
-cc    -c -o b.o b.c
-    Successfully remade target file `b.o'.
-   Finished prerequisites of target file `fred.in'.
-  Must remake target `fred.in'.
-  Successfully remade target file `fred.in'.
- Finished prerequisites of target file `fred.exe'.
-Must remake target `fred.exe'.
-Successfully remade target file `fred.exe'.
-"""
-
-"""
-Considering target file `/var/local/net/smb/tmurphy/pf/mcloverlay/common/generic/COMMS-INFRAS/ESOCK/commsdataobjects/src/provinfoqueryset.cpp'.
-         Finished prerequisites of target file `/var/local/net/smb/tmurphy/pf/mcloverlay/common/generic/COMMS-INFRAS/ESOC
-K/commsdataobjects/src/provinfoqueryset.cpp'.
-"""
-
-# The output is a filename followed by a number.  If the number is 0
-# Then the prerequisites that file now exist.
-# If > 0 then the prerequisites for that file could not be completed.
-
-import sys
-from  optparse import OptionParser
-import re
-import os
-from stat import *
-
-def findfailed(file):
-	""" Find unbuilt files and prioritise them.  
-	    Higher numbers go to files that didn't fail because
-	    of prerequisites.
-
-	    Rationale: files that failed because their prerequisites
-	    failed are worth knowing about but cannot themselves be addressed.
-	"""
-	filecount = {}
-	extre = re.compile(".*\.(?P<ext>[^'\/\"]+)$", re.I)
-	startre = re.compile("[\t ]*File `(?P<file>[^']*)\' does not exist.*", re.I)
-	zerore = re.compile("[\t ]*Successfully remade target file `(?P<file>[^']*)'\..*", re.I)
-	#endre = re.compile("[\t ]*Finished prerequisites of target file `(?P<file>[^']*)'\..*", re.I)
-	endre = re.compile("[\t ]*Giving up on target file `(?P<file>[^']*)'\..*", re.I)
-
-	for x in file.readlines():
-		g = startre.match(x)
-		if g is not None:
-			filename = g.group('file').strip('"')
-			eg = extre.match(filename)
-			if eg is not None:
-				filecount[filename] = [1, eg.group('ext')]
-			else:
-				filecount[filename] = [1, "none"]
-
-		else:
-			g = zerore.match(x)
-			if g is not None:
-				# Complete success - not interesting.
-				filename = g.group('file').strip('"')
-				if filename in filecount:
-					del filecount[filename]
-			else:
-				g = endre.match(x)
-				if g is not None:
-					# did manage to make the prerequisites, perhaps not the file
-					filename = g.group('file').strip('"')
-					if filename in filecount:
-						filecount[filename][0] = 2
-	return filecount
-
-def showtargets(targets,prereq):
-	output=[]	
-	for k in targets:
-		l = "%s\t%i\t%s" % (targets[k][1], targets[k][0], k)
-		if prereq:
-			if targets[k][0] == 2:
-				# There were missing pre-requisites
-				output.append(l)
-		else:
-				output.append(l)
-	output.sort()
-	for o in output:
-		sys.stdout.write("%s\n" % o)
-
-def readmake(file):
-	rule = re.compile("^[^ :$]*:[^=]", re.I)
-	for x in file.readlines():
-		g = startre.match(x)
-		if g is not None:
-			filename = g.group('file').strip('"')
-			eg = extre.match(filename)
-			if eg is not None:
-				ext = eg.group('ext')
-			else:
-				ext = "none"
-
-
-
-parser = OptionParser(prog = "matchmade",
-	usage = "%prog [-h | options] [ -d make database filename ] logfile")
-
-parser.add_option("-m", "--missing-prerequistes", default = False,
-	 action="store_true", dest="missing", help="List those targets whose pre-requisites could not be found or made") 
-
-parser.add_option("-d","--make-db",action="store",dest="makedb",
-                                help="name of make database")
-
-(options, args) = parser.parse_args()
-
-logname="stdin"
-if len(args) > 0:
-        logname=args[0]
-        file = open(logname,"r")
-else:
-        file = sys.stdin
-
-showtargets(findfailed(file),options.missing)
-#assistmake(file,options.missing)
-
-if file != sys.stdin:
-	file.close()
+#
+# 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: 
+# Generate some useful statistics from a Raptor build log
+# Work out what was specified to make but not built even if
+# it was not mentioned in the make error output because some
+# child's dependency was not satisfied.
+# Needs raptor --tracking option to set make to use -debug=v
+# An example bit of make output that can be analysed:
+#
+
+ File `fred.exe' does not exist.
+  Considering target file `fred.in'.
+   File `fred.in' does not exist.
+    Considering target file `a.o'.
+     File `a.o' does not exist.
+      Considering target file `a.c'.
+       Finished prerequisites of target file `a.c'.
+      No need to remake target `a.c'.
+      Pruning file `a.c'.
+     Finished prerequisites of target file `a.o'.
+    Must remake target `a.o'.
+cc    -c -o a.o a.c
+    Successfully remade target file `a.o'.
+    Considering target file `b.o'.
+     File `b.o' does not exist.
+      Considering target file `b.c'.
+       Finished prerequisites of target file `b.c'.
+      No need to remake target `b.c'.
+      Pruning file `b.c'.
+     Finished prerequisites of target file `b.o'.
+    Must remake target `b.o'.
+cc    -c -o b.o b.c
+    Successfully remade target file `b.o'.
+   Finished prerequisites of target file `fred.in'.
+  Must remake target `fred.in'.
+  Successfully remade target file `fred.in'.
+ Finished prerequisites of target file `fred.exe'.
+Must remake target `fred.exe'.
+Successfully remade target file `fred.exe'.
+"""
+
+"""
+Considering target file `/var/local/net/smb/tmurphy/pf/mcloverlay/common/generic/COMMS-INFRAS/ESOCK/commsdataobjects/src/provinfoqueryset.cpp'.
+         Finished prerequisites of target file `/var/local/net/smb/tmurphy/pf/mcloverlay/common/generic/COMMS-INFRAS/ESOC
+K/commsdataobjects/src/provinfoqueryset.cpp'.
+"""
+
+# The output is a filename followed by a number.  If the number is 0
+# Then the prerequisites that file now exist.
+# If > 0 then the prerequisites for that file could not be completed.
+
+import sys
+from  optparse import OptionParser
+import re
+import os
+from stat import *
+
+def findfailed(file):
+	""" Find unbuilt files and prioritise them.  
+	    Higher numbers go to files that didn't fail because
+	    of prerequisites.
+
+	    Rationale: files that failed because their prerequisites
+	    failed are worth knowing about but cannot themselves be addressed.
+	"""
+	filecount = {}
+	extre = re.compile(".*\.(?P<ext>[^'\/\"]+)$", re.I)
+	startre = re.compile("[\t ]*File `(?P<file>[^']*)\' does not exist.*", re.I)
+	zerore = re.compile("[\t ]*Successfully remade target file `(?P<file>[^']*)'\..*", re.I)
+	#endre = re.compile("[\t ]*Finished prerequisites of target file `(?P<file>[^']*)'\..*", re.I)
+	endre = re.compile("[\t ]*Giving up on target file `(?P<file>[^']*)'\..*", re.I)
+
+	for x in file.readlines():
+		g = startre.match(x)
+		if g is not None:
+			filename = g.group('file').strip('"')
+			eg = extre.match(filename)
+			if eg is not None:
+				filecount[filename] = [1, eg.group('ext')]
+			else:
+				filecount[filename] = [1, "none"]
+
+		else:
+			g = zerore.match(x)
+			if g is not None:
+				# Complete success - not interesting.
+				filename = g.group('file').strip('"')
+				if filename in filecount:
+					del filecount[filename]
+			else:
+				g = endre.match(x)
+				if g is not None:
+					# did manage to make the prerequisites, perhaps not the file
+					filename = g.group('file').strip('"')
+					if filename in filecount:
+						filecount[filename][0] = 2
+	return filecount
+
+def showtargets(targets,prereq):
+	output=[]	
+	for k in targets:
+		l = "%s\t%i\t%s" % (targets[k][1], targets[k][0], k)
+		if prereq:
+			if targets[k][0] == 2:
+				# There were missing pre-requisites
+				output.append(l)
+		else:
+				output.append(l)
+	output.sort()
+	for o in output:
+		sys.stdout.write("%s\n" % o)
+
+def readmake(file):
+	rule = re.compile("^[^ :$]*:[^=]", re.I)
+	for x in file.readlines():
+		g = startre.match(x)
+		if g is not None:
+			filename = g.group('file').strip('"')
+			eg = extre.match(filename)
+			if eg is not None:
+				ext = eg.group('ext')
+			else:
+				ext = "none"
+
+
+
+parser = OptionParser(prog = "matchmade",
+	usage = "%prog [-h | options] [ -d make database filename ] logfile")
+
+parser.add_option("-m", "--missing-prerequistes", default = False,
+	 action="store_true", dest="missing", help="List those targets whose pre-requisites could not be found or made") 
+
+parser.add_option("-d","--make-db",action="store",dest="makedb",
+                                help="name of make database")
+
+(options, args) = parser.parse_args()
+
+logname="stdin"
+if len(args) > 0:
+        logname=args[0]
+        file = open(logname,"r")
+else:
+        file = sys.stdin
+
+showtargets(findfailed(file),options.missing)
+#assistmake(file,options.missing)
+
+if file != sys.stdin:
+	file.close()
--- a/sbsv2/raptor/bin/fixmeta.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/fixmeta.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,81 +1,81 @@
-#
-# 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: 
-# fixmeta
-#
-
-"""
-  Correct bld.infs, mmps etc to the point where it can be read by the build system
-  Currently it:
-  	Corrects '\' in include statements to '/'
-
-  Author: Tim Murphy, with a nod to Peter Harper's fixslashes.pl
-"""
-
-import sys
-import os
-import re
-from  optparse import OptionParser
-
-
-includeslash_re = re.compile('#include.*\\\\')
-mmpfile_re = re.compile(".*\.mm[hp]$", re.I)
-bldinf_re = re.compile(".*bld\.inf$", re.I)
-
-def fixincludeslash(m):
-	return m.group(0).replace('\\','/')
-	
-
-def checkconvert(dirname, filename):
-	tofilename=dirname + "/" + filename+".converted"
-	fromfilename = dirname + "/" + filename
-	fromfile = open(fromfilename,"r")
-
-	conversions = False
-	fromtext = fromfile.read()
-	(totext, subcount) = re.subn(includeslash_re, fixincludeslash, fromtext)
-
-	if subcount != 0:
-		print '"%s", %d backslash includes\n' % (fromfilename, subcount)
-		tofile = open( tofilename,"w")
-		tofile.write(totext)
-		tofile.close()
-
-	fromfile.close()
-	if subcount != 0:
-		os.rename(fromfilename,fromfilename+".wrongslash")
-		os.rename(tofilename,fromfilename)
-	
-	
-
-def visit(arg, dirname, names):
-	#print "dir: %s\n" % (dirname)
-	for f in names:
-		m = mmpfile_re.match(f)
-		b = bldinf_re.match(f)
-		if m != None or b != None:
-			#print "\t"+f
-			checkconvert(dirname, f)
-
-parser = OptionParser(prog = "fixmeta",
-        usage = "%prog [-h | options] sourcepath containing files to be fixed.")
-
-(options, args) = parser.parse_args()
-
-if len(args) == 0:
-	print "Need at least one argument: a path to the source which is to be fixed."
-	sys.exit(-1)
-
-print "Walking\n"
-os.path.walk(args[0],visit,None)
+#
+# 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: 
+# fixmeta
+#
+
+"""
+  Correct bld.infs, mmps etc to the point where it can be read by the build system
+  Currently it:
+  	Corrects '\' in include statements to '/'
+
+  Author: Tim Murphy, with a nod to Peter Harper's fixslashes.pl
+"""
+
+import sys
+import os
+import re
+from  optparse import OptionParser
+
+
+includeslash_re = re.compile('#include.*\\\\')
+mmpfile_re = re.compile(".*\.mm[hp]$", re.I)
+bldinf_re = re.compile(".*bld\.inf$", re.I)
+
+def fixincludeslash(m):
+	return m.group(0).replace('\\','/')
+	
+
+def checkconvert(dirname, filename):
+	tofilename=dirname + "/" + filename+".converted"
+	fromfilename = dirname + "/" + filename
+	fromfile = open(fromfilename,"r")
+
+	conversions = False
+	fromtext = fromfile.read()
+	(totext, subcount) = re.subn(includeslash_re, fixincludeslash, fromtext)
+
+	if subcount != 0:
+		print '"%s", %d backslash includes\n' % (fromfilename, subcount)
+		tofile = open( tofilename,"w")
+		tofile.write(totext)
+		tofile.close()
+
+	fromfile.close()
+	if subcount != 0:
+		os.rename(fromfilename,fromfilename+".wrongslash")
+		os.rename(tofilename,fromfilename)
+	
+	
+
+def visit(arg, dirname, names):
+	#print "dir: %s\n" % (dirname)
+	for f in names:
+		m = mmpfile_re.match(f)
+		b = bldinf_re.match(f)
+		if m != None or b != None:
+			#print "\t"+f
+			checkconvert(dirname, f)
+
+parser = OptionParser(prog = "fixmeta",
+        usage = "%prog [-h | options] sourcepath containing files to be fixed.")
+
+(options, args) = parser.parse_args()
+
+if len(args) == 0:
+	print "Need at least one argument: a path to the source which is to be fixed."
+	sys.exit(-1)
+
+print "Walking\n"
+os.path.walk(args[0],visit,None)
--- a/sbsv2/raptor/bin/install_raptor.sh	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/install_raptor.sh	Wed Jun 23 16:56:47 2010 +0800
@@ -1,187 +1,187 @@
-#!/bin/bash
-# raptor script
-
-# install sbsv2
-
-chmod a+x "${PWD}/bin/gethost.sh"
-export HOSTPLATFORM=$("$PWD/bin/gethost.sh")
-export HOSTPLATFORM_DIR=$("$PWD/bin/gethost.sh" -d)
-
-export build_utils=no
-if [[ ! -d "$PWD/$HOSTPLATFORM_DIR" ]]; then
-cat << MSG
-
-The Raptor installer has determined that this computer is running:
-	$HOSTPLATFORM_DIR
-This platform is not directly supported by the installer.
-
-If you proceed then the installation will attempt to build the Raptor tools for your platform.
-
-Your system must have some tools installed:
-MSG
-
-if [ "$(which gcc)" ]; then
-   echo "You appear to have gcc"
-else
-   echo "You DON'T appear to have gcc - please install it"
-fi
-
-if [ "$(which g++)" ]; then
-   echo "You appear to have gcc-c++"
-else
-   echo "You DON'T appear to have gcc-c++ (also called g++) - please install it"
-fi
-
-if [ "$(which make)" ]; then
-   echo "You appear to have GNU make"
-else
-   echo "You DON'T appear to have GNU make - please install it (version 3.81)"
-fi
-
-if [ "$(which bison)" ]; then
-   echo "You appear to have GNU bison"
-else
-   echo "You DON'T appear to have GNU bison - please install it "
-fi
-
-if [ -f "/usr/include/ncurses.h" ]; then
-   echo "You appear to have the ncurses dev libraries"
-else
-   echo "You DON'T appear to have the ncurses dev libraries - please install them (ncurses-dev or ncurses-devel)"
-fi
-
-echo "Do you wish to continue (Y or y for 'yes' anything else for no)?"
-
-read X
-if [[  "$X" != "y" && "$X" != "Y" ]]; then
-	exit 1
-else
-	build_utils=yes
-fi
-
-
-# Build the dialog utility so that we can get started
-(export SBS_HOME=$PWD;cd "$SBS_HOME/util" && echo "Building dialog utility..." && (make -k -j2 dialog> dialog_util_build.log 2>&1 && echo -e "\nBuild Complete") || (echo "Dialog utility build failed, see $PWD/dialog_util_build.log for more details"; read X; exit 1)) || exit 1
-
-fi
-
-
-export DIALOG="$PWD/$HOSTPLATFORM_DIR/bin/dialog"
-chmod a+x "$DIALOG"
-
-export SYMBIANHOME=/opt/symbian
-
-test -w "$SYMBIANHOME"
-if [[ $? -ne 0 ]]; then
-SYMBIANHOME=$(echo ~)
-fi
-
-export TMPSBSDIR="$PWD"
-
-errorexit() {
-        echo -e "\nRaptor installation aborted: $1" 1>&2
-	echo -e "\nInstall tmp dir is $TMPSBSDIR" 1>&2
-	exit 1
-	}
-	
-
-# get FULLVERSION and VERSION
-export FULLVERSION=""
-export VERSION=""
-eval $(cat .version)
-
-
-if [[ "$FULLVERSION" == "" || "$VERSION" == "" ]]; then
-	errorexit "Bad install package - no version found." 
-fi
-
-
-export RESPONSEFILE=$PWD/.installdir
-export MANIFEST=$PWD/.manifest
-export SBS_HOME=$SYMBIANHOME/raptor-$(echo "$VERSION" | sed 's#\.##g')
-
-DIALOGVER=$($DIALOG --version)
-
-if  ! expr match "$DIALOGVER" "Version:" 2>&1 >/dev/null; then
-	errorexit "Could not run the installation user interface on this version of Linux.\nPlease install the compat-glibc and compat-ncurses packages (RedHat) or the equivalent for your distribution and then try again.\n\nYou may also simply 'untar' raptor using the ' --target NewDirectory --noexec' options to this installer.\n"
-fi
-	
-
-export DIALOGSBS=$DIALOG "--backtitle 'Installing $FULLVERSION'"
-
-$DIALOGSBS --msgbox "Symbian Build System Installer\n\n$FULLVERSION" 0 0
-
-# check what SBS_HOME
-$DIALOGSBS --title "Select Symbian Home Directory" --fselect  "$SBS_HOME"  10 50   2> "$RESPONSEFILE"
-SBS_HOME=$(cat "$RESPONSEFILE")
-
-
-if [[ ! -d "$SBS_HOME" ]]; then
-	$DIALOGSBS --yesno  "$SBS_HOME does not exist - should it be created?" 0 0; YESNO=$?
-	if [[ "$YESNO" -eq 0 ]]; then
-		mkdir -p "$SBS_HOME" || 
-		(
-			errorexit "Could not create directory $SBS_HOME"
-		)
-	else
-		errorexit "SBSv2 Installation aborted: User chose not to create installation directory $SBS_HOME" 
-	fi
-else
-	# check if there's a previous install and give an option to stop
-	$DIALOGSBS --defaultno --yesno  "$SBS_HOME already exists - should the installation be overwritten?" 0 0; YESNO=$?
-	if [[ "$YESNO" -eq 1 ]]; then
-		errorexit "Not replacing existing installation." 
-	fi
-fi
-
-# Install the software
-echo "" >"$MANIFEST"
-(tar -cf - *) | (cd $SBS_HOME && tar -xvf - > "$MANIFEST" && echo -e "\nCopying complete - press RETURN" >> "$MANIFEST") &
-(
-$DIALOGSBS --title "Copying SBS files" --tailbox "$MANIFEST" 20 60 
-)
-
-# Build the utilities if needed 
-if [[ "$build_utils" == "yes" ]]; then
-BUILDLOG=$SBS_HOME/util/util_build.log
-(cd "$SBS_HOME/util" && echo "Building utilities ..." && make -k -j2  
-if [[ $? -eq 0 ]]; then
-	echo -e "\nBuild Complete" 
-else
-	echo -e "\nUtility build failed, see $BUILDLOG for more details"
-	exit 1
-fi
-) > "$BUILDLOG" 2>&1  & (
-$DIALOGSBS --title "Building utilities for $HOSTPLATFORM_DIR" --tailbox "$BUILDLOG" 20 60 
-)
-fi
-
-
-# Force sbs to be executable:
-chmod a+x "${SBS_HOME}/bin/sbs"
-chmod a+x "${SBS_HOME}/bin/gethost.sh"
-chmod a+x "${SBS_HOME}/bin/setup_user.sh"
-chmod -R a+r "${SBS_HOME}"
-chmod a+x "${SBS_HOME}/$HOSTPLATFORM_DIR/bin/"*
-chmod a+x "${SBS_HOME}/$HOSTPLATFORM_DIR/bv/bin/"* 
-chmod a+x "${SBS_HOME}/$HOSTPLATFORM_DIR/bv/libexec/"*/*/*
-
-
-# Prepare user scripts for bashrc and bash_profile
-INSTALLER="${SBS_HOME}/util/install-linux"
-sed "s#__SBS_HOME__#${SBS_HOME}#" < "${INSTALLER}/linux_bash_profile" > "${SBS_HOME}/bin/user.bash_profile"
-sed "s#__SBS_HOME__#${SBS_HOME}#" < "${INSTALLER}/linux_bashrc" > "${SBS_HOME}/bin/user.bashrc"
-
-# Set symbolic Link
-if [[ -L "$SYMBIANHOME/raptor" ]]; then
-	rm "$SYMBIANHOME/raptor"
-fi
-
-if [[ ! -e "$SYMBIANHOME/raptor" ]]; then
-	ln -s  "$SBS_HOME" "$SYMBIANHOME/raptor"
-fi
-
-
-$DIALOGSBS --msgbox "Raptor $VERSION\ninstallation complete" 0 0
-
-
+#!/bin/bash
+# raptor script
+
+# install sbsv2
+
+chmod a+x "${PWD}/bin/gethost.sh"
+export HOSTPLATFORM=$("$PWD/bin/gethost.sh")
+export HOSTPLATFORM_DIR=$("$PWD/bin/gethost.sh" -d)
+
+export build_utils=no
+if [[ ! -d "$PWD/$HOSTPLATFORM_DIR" ]]; then
+cat << MSG
+
+The Raptor installer has determined that this computer is running:
+	$HOSTPLATFORM_DIR
+This platform is not directly supported by the installer.
+
+If you proceed then the installation will attempt to build the Raptor tools for your platform.
+
+Your system must have some tools installed:
+MSG
+
+if [ "$(which gcc)" ]; then
+   echo "You appear to have gcc"
+else
+   echo "You DON'T appear to have gcc - please install it"
+fi
+
+if [ "$(which g++)" ]; then
+   echo "You appear to have gcc-c++"
+else
+   echo "You DON'T appear to have gcc-c++ (also called g++) - please install it"
+fi
+
+if [ "$(which make)" ]; then
+   echo "You appear to have GNU make"
+else
+   echo "You DON'T appear to have GNU make - please install it (version 3.81)"
+fi
+
+if [ "$(which bison)" ]; then
+   echo "You appear to have GNU bison"
+else
+   echo "You DON'T appear to have GNU bison - please install it "
+fi
+
+if [ -f "/usr/include/ncurses.h" ]; then
+   echo "You appear to have the ncurses dev libraries"
+else
+   echo "You DON'T appear to have the ncurses dev libraries - please install them (ncurses-dev or ncurses-devel)"
+fi
+
+echo "Do you wish to continue (Y or y for 'yes' anything else for no)?"
+
+read X
+if [[  "$X" != "y" && "$X" != "Y" ]]; then
+	exit 1
+else
+	build_utils=yes
+fi
+
+
+# Build the dialog utility so that we can get started
+(export SBS_HOME=$PWD;cd "$SBS_HOME/util" && echo "Building dialog utility..." && (make -k -j2 dialog> dialog_util_build.log 2>&1 && echo -e "\nBuild Complete") || (echo "Dialog utility build failed, see $PWD/dialog_util_build.log for more details"; read X; exit 1)) || exit 1
+
+fi
+
+
+export DIALOG="$PWD/$HOSTPLATFORM_DIR/bin/dialog"
+chmod a+x "$DIALOG"
+
+export SYMBIANHOME=/opt/symbian
+
+test -w "$SYMBIANHOME"
+if [[ $? -ne 0 ]]; then
+SYMBIANHOME=$(echo ~)
+fi
+
+export TMPSBSDIR="$PWD"
+
+errorexit() {
+        echo -e "\nRaptor installation aborted: $1" 1>&2
+	echo -e "\nInstall tmp dir is $TMPSBSDIR" 1>&2
+	exit 1
+	}
+	
+
+# get FULLVERSION and VERSION
+export FULLVERSION=""
+export VERSION=""
+eval $(cat .version)
+
+
+if [[ "$FULLVERSION" == "" || "$VERSION" == "" ]]; then
+	errorexit "Bad install package - no version found." 
+fi
+
+
+export RESPONSEFILE=$PWD/.installdir
+export MANIFEST=$PWD/.manifest
+export SBS_HOME=$SYMBIANHOME/raptor-$(echo "$VERSION" | sed 's#\.##g')
+
+DIALOGVER=$($DIALOG --version)
+
+if  ! expr match "$DIALOGVER" "Version:" 2>&1 >/dev/null; then
+	errorexit "Could not run the installation user interface on this version of Linux.\nPlease install the compat-glibc and compat-ncurses packages (RedHat) or the equivalent for your distribution and then try again.\n\nYou may also simply 'untar' raptor using the ' --target NewDirectory --noexec' options to this installer.\n"
+fi
+	
+
+export DIALOGSBS=$DIALOG "--backtitle 'Installing $FULLVERSION'"
+
+$DIALOGSBS --msgbox "Symbian Build System Installer\n\n$FULLVERSION" 0 0
+
+# check what SBS_HOME
+$DIALOGSBS --title "Select Symbian Home Directory" --fselect  "$SBS_HOME"  10 50   2> "$RESPONSEFILE"
+SBS_HOME=$(cat "$RESPONSEFILE")
+
+
+if [[ ! -d "$SBS_HOME" ]]; then
+	$DIALOGSBS --yesno  "$SBS_HOME does not exist - should it be created?" 0 0; YESNO=$?
+	if [[ "$YESNO" -eq 0 ]]; then
+		mkdir -p "$SBS_HOME" || 
+		(
+			errorexit "Could not create directory $SBS_HOME"
+		)
+	else
+		errorexit "SBSv2 Installation aborted: User chose not to create installation directory $SBS_HOME" 
+	fi
+else
+	# check if there's a previous install and give an option to stop
+	$DIALOGSBS --defaultno --yesno  "$SBS_HOME already exists - should the installation be overwritten?" 0 0; YESNO=$?
+	if [[ "$YESNO" -eq 1 ]]; then
+		errorexit "Not replacing existing installation." 
+	fi
+fi
+
+# Install the software
+echo "" >"$MANIFEST"
+(tar -cf - *) | (cd $SBS_HOME && tar -xvf - > "$MANIFEST" && echo -e "\nCopying complete - press RETURN" >> "$MANIFEST") &
+(
+$DIALOGSBS --title "Copying SBS files" --tailbox "$MANIFEST" 20 60 
+)
+
+# Build the utilities if needed 
+if [[ "$build_utils" == "yes" ]]; then
+BUILDLOG=$SBS_HOME/util/util_build.log
+(cd "$SBS_HOME/util" && echo "Building utilities ..." && make -k -j2  
+if [[ $? -eq 0 ]]; then
+	echo -e "\nBuild Complete" 
+else
+	echo -e "\nUtility build failed, see $BUILDLOG for more details"
+	exit 1
+fi
+) > "$BUILDLOG" 2>&1  & (
+$DIALOGSBS --title "Building utilities for $HOSTPLATFORM_DIR" --tailbox "$BUILDLOG" 20 60 
+)
+fi
+
+
+# Force sbs to be executable:
+chmod a+x "${SBS_HOME}/bin/sbs"
+chmod a+x "${SBS_HOME}/bin/gethost.sh"
+chmod a+x "${SBS_HOME}/bin/setup_user.sh"
+chmod -R a+r "${SBS_HOME}"
+chmod a+x "${SBS_HOME}/$HOSTPLATFORM_DIR/bin/"*
+chmod a+x "${SBS_HOME}/$HOSTPLATFORM_DIR/bv/bin/"* 
+chmod a+x "${SBS_HOME}/$HOSTPLATFORM_DIR/bv/libexec/"*/*/*
+
+
+# Prepare user scripts for bashrc and bash_profile
+INSTALLER="${SBS_HOME}/util/install-linux"
+sed "s#__SBS_HOME__#${SBS_HOME}#" < "${INSTALLER}/linux_bash_profile" > "${SBS_HOME}/bin/user.bash_profile"
+sed "s#__SBS_HOME__#${SBS_HOME}#" < "${INSTALLER}/linux_bashrc" > "${SBS_HOME}/bin/user.bashrc"
+
+# Set symbolic Link
+if [[ -L "$SYMBIANHOME/raptor" ]]; then
+	rm "$SYMBIANHOME/raptor"
+fi
+
+if [[ ! -e "$SYMBIANHOME/raptor" ]]; then
+	ln -s  "$SBS_HOME" "$SYMBIANHOME/raptor"
+fi
+
+
+$DIALOGSBS --msgbox "Raptor $VERSION\ninstallation complete" 0 0
+
+
--- a/sbsv2/raptor/bin/mkgetfailed.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/mkgetfailed.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,111 +1,111 @@
-#
-# 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: 
-# Generate some useful statistics from a Raptor build log
-# Work out what was specified to make but not built even if
-# it was not mentioned in the make error output because some
-# child's dependency was not satisfied.
-# Needs raptor --tracking option to set make to use -debug=v
-# An example bit of make output that can be analysed:
-#
-
- File `fred.exe' does not exist.
-  Considering target file `fred.in'.
-   File `fred.in' does not exist.
-    Considering target file `a.o'.
-     File `a.o' does not exist.
-      Considering target file `a.c'.
-       Finished prerequisites of target file `a.c'.
-      No need to remake target `a.c'.
-      Pruning file `a.c'.
-     Finished prerequisites of target file `a.o'.
-    Must remake target `a.o'.
-cc    -c -o a.o a.c
-    Successfully remade target file `a.o'.
-    Considering target file `b.o'.
-     File `b.o' does not exist.
-      Considering target file `b.c'.
-       Finished prerequisites of target file `b.c'.
-      No need to remake target `b.c'.
-      Pruning file `b.c'.
-     Finished prerequisites of target file `b.o'.
-    Must remake target `b.o'.
-cc    -c -o b.o b.c
-    Successfully remade target file `b.o'.
-   Finished prerequisites of target file `fred.in'.
-  Must remake target `fred.in'.
-  Successfully remade target file `fred.in'.
- Finished prerequisites of target file `fred.exe'.
-Must remake target `fred.exe'.
-Successfully remade target file `fred.exe'.
-"""
-
-# The output is a filename followed by a number.  If the number is 0
-# Then the prerequisites that file now exist.
-# If > 0 then the prerequisites for that file could not be completed.
-
-import sys
-from  optparse import OptionParser
-import re
-import os
-from stat import *
-
-def genstats(file,showmissing):
-	filecount = {}
-	startre = re.compile("[\t ]*File `(?P<file>[^']*)' does not exist")
-	endre = re.compile("[\t ]*Finished prerequisites of target file `(?P<file>[^']*)'\..*")
-	for x in file.readlines():
-		g = startre.match(x)
-		if g is not None:
-			filename = g.group('file')
-			try:
-				filecount[filename] += 1
-			except KeyError:
-				filecount[filename] = 1
-		else:
-			g = endre.match(x)
-			if g is not None:
-				filename = g.group('file')
-				try:
-					filecount[filename] -= 1
-				except KeyError:
-					filecount[filename] = 0
-	
-	for k in filecount:
-		if showmissing:
-			if filecount[k] > 0:
-				print "%s: %i" % (k,filecount[k])
-		else:
-			print "%s: %i" % (k,filecount[k])
-
-
-parser = OptionParser(prog = "matchmade",
-	usage = "%prog [-h | options] logfile")
-
-parser.add_option("-m", "--missing-prerequistes", default = False,
-	 action="store_true", dest="missing", help="List those targets whose pre-requisites could not be found or made") 
-
-(options, args) = parser.parse_args()
-
-logname="stdin"
-if len(args) > 0:
-	logname=args[0]
-	file = open(logname,"r")
-else:
-	file = sys.stdin
-
-genstats(file,options.missing)
-
-if file != sys.stdin:
-	file.close()
+#
+# 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: 
+# Generate some useful statistics from a Raptor build log
+# Work out what was specified to make but not built even if
+# it was not mentioned in the make error output because some
+# child's dependency was not satisfied.
+# Needs raptor --tracking option to set make to use -debug=v
+# An example bit of make output that can be analysed:
+#
+
+ File `fred.exe' does not exist.
+  Considering target file `fred.in'.
+   File `fred.in' does not exist.
+    Considering target file `a.o'.
+     File `a.o' does not exist.
+      Considering target file `a.c'.
+       Finished prerequisites of target file `a.c'.
+      No need to remake target `a.c'.
+      Pruning file `a.c'.
+     Finished prerequisites of target file `a.o'.
+    Must remake target `a.o'.
+cc    -c -o a.o a.c
+    Successfully remade target file `a.o'.
+    Considering target file `b.o'.
+     File `b.o' does not exist.
+      Considering target file `b.c'.
+       Finished prerequisites of target file `b.c'.
+      No need to remake target `b.c'.
+      Pruning file `b.c'.
+     Finished prerequisites of target file `b.o'.
+    Must remake target `b.o'.
+cc    -c -o b.o b.c
+    Successfully remade target file `b.o'.
+   Finished prerequisites of target file `fred.in'.
+  Must remake target `fred.in'.
+  Successfully remade target file `fred.in'.
+ Finished prerequisites of target file `fred.exe'.
+Must remake target `fred.exe'.
+Successfully remade target file `fred.exe'.
+"""
+
+# The output is a filename followed by a number.  If the number is 0
+# Then the prerequisites that file now exist.
+# If > 0 then the prerequisites for that file could not be completed.
+
+import sys
+from  optparse import OptionParser
+import re
+import os
+from stat import *
+
+def genstats(file,showmissing):
+	filecount = {}
+	startre = re.compile("[\t ]*File `(?P<file>[^']*)' does not exist")
+	endre = re.compile("[\t ]*Finished prerequisites of target file `(?P<file>[^']*)'\..*")
+	for x in file.readlines():
+		g = startre.match(x)
+		if g is not None:
+			filename = g.group('file')
+			try:
+				filecount[filename] += 1
+			except KeyError:
+				filecount[filename] = 1
+		else:
+			g = endre.match(x)
+			if g is not None:
+				filename = g.group('file')
+				try:
+					filecount[filename] -= 1
+				except KeyError:
+					filecount[filename] = 0
+	
+	for k in filecount:
+		if showmissing:
+			if filecount[k] > 0:
+				print "%s: %i" % (k,filecount[k])
+		else:
+			print "%s: %i" % (k,filecount[k])
+
+
+parser = OptionParser(prog = "matchmade",
+	usage = "%prog [-h | options] logfile")
+
+parser.add_option("-m", "--missing-prerequistes", default = False,
+	 action="store_true", dest="missing", help="List those targets whose pre-requisites could not be found or made") 
+
+(options, args) = parser.parse_args()
+
+logname="stdin"
+if len(args) > 0:
+	logname=args[0]
+	file = open(logname,"r")
+else:
+	file = sys.stdin
+
+genstats(file,options.missing)
+
+if file != sys.stdin:
+	file.close()
--- a/sbsv2/raptor/bin/oby2linux.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/oby2linux.py	Wed Jun 23 16:56:47 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: 
-# oby2linux
-#
-
-"""
-  Convert an OBY file into a form that rombuild on Linux can use.
-  This involves converting paths etc.  In addition it finds those target
-  files whose case may not match what exists on the filesystem
-  (a build must have been completed).
- 
-  It also fills in those items that weren't built from a directory 
-  containing a prebuild epoc32 dir.
-"""
-
-
-import sys
-import os
-import re
-
-sys.path.append(os.environ['SBS_HOME']+'/python')
-import generic_path
-
-epocroot = os.environ['EPOCROOT']
-
-try:
-	romfillin_epocroot = os.environ['ROMFILLIN_EPOCROOT']
-except:
-	sys.stderr.write("Please set ROMFILLIN_EPOCROOT to a path with an epoc32 directory\n")
-	sys.exit(1)
-
-if not os.path.isdir(romfillin_epocroot+'/epoc32'):
-	sys.stderr.write("Please set ROMFILLIN_EPOCROOT to a path with an epoc32 directory\n")
-	sys.exit(1)
-
-filestatement_re=re.compile("^(?P<pre>((((primary)|(secondary)|(extension)|(device)|(variant))(\[0x[0-9a-zA-Z]+\])?=)|((file)|(data)|(bootbinary))=))(?P<filename>\S+)(?P<tail>.*)$")
-
-for line in sys.stdin.xreadlines():
-	line = line.rstrip()
-	m = filestatement_re.search(line)
-	if m is not None:
-		fname =  m.groupdict()['filename'].replace('\\','/').strip('"')
-		filename = generic_path.Path(epocroot + fname)
-		filefound = filename.FindCaseless()
-		if filefound is not None:
-			print m.groupdict()['pre'] + str(filefound) + m.groupdict()['tail']
-			#print filefound
-		else:
-			fillinname = generic_path.Path(romfillin_epocroot+fname)
-			filefound =  fillinname.FindCaseless()
-			if filefound is not None:
-				sys.stderr.write("filledinmissing: %s\n" % str(filefound))
-				print m.groupdict()['pre'] + str(filefound) + m.groupdict()['tail']
-				#print filefound
-			else:
-				sys.stderr.write("filenotfound: %s\n" % str(filename))
-	else:
-		print line
-
-	
-
+#
+# 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: 
+# oby2linux
+#
+
+"""
+  Convert an OBY file into a form that rombuild on Linux can use.
+  This involves converting paths etc.  In addition it finds those target
+  files whose case may not match what exists on the filesystem
+  (a build must have been completed).
+ 
+  It also fills in those items that weren't built from a directory 
+  containing a prebuild epoc32 dir.
+"""
+
+
+import sys
+import os
+import re
+
+sys.path.append(os.environ['SBS_HOME']+'/python')
+import generic_path
+
+epocroot = os.environ['EPOCROOT']
+
+try:
+	romfillin_epocroot = os.environ['ROMFILLIN_EPOCROOT']
+except:
+	sys.stderr.write("Please set ROMFILLIN_EPOCROOT to a path with an epoc32 directory\n")
+	sys.exit(1)
+
+if not os.path.isdir(romfillin_epocroot+'/epoc32'):
+	sys.stderr.write("Please set ROMFILLIN_EPOCROOT to a path with an epoc32 directory\n")
+	sys.exit(1)
+
+filestatement_re=re.compile("^(?P<pre>((((primary)|(secondary)|(extension)|(device)|(variant))(\[0x[0-9a-zA-Z]+\])?=)|((file)|(data)|(bootbinary))=))(?P<filename>\S+)(?P<tail>.*)$")
+
+for line in sys.stdin.xreadlines():
+	line = line.rstrip()
+	m = filestatement_re.search(line)
+	if m is not None:
+		fname =  m.groupdict()['filename'].replace('\\','/').strip('"')
+		filename = generic_path.Path(epocroot + fname)
+		filefound = filename.FindCaseless()
+		if filefound is not None:
+			print m.groupdict()['pre'] + str(filefound) + m.groupdict()['tail']
+			#print filefound
+		else:
+			fillinname = generic_path.Path(romfillin_epocroot+fname)
+			filefound =  fillinname.FindCaseless()
+			if filefound is not None:
+				sys.stderr.write("filledinmissing: %s\n" % str(filefound))
+				print m.groupdict()['pre'] + str(filefound) + m.groupdict()['tail']
+				#print filefound
+			else:
+				sys.stderr.write("filenotfound: %s\n" % str(filename))
+	else:
+		print line
+
+	
+
--- a/sbsv2/raptor/bin/osbuild.sh	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/osbuild.sh	Wed Jun 23 16:56:47 2010 +0800
@@ -1,264 +1,264 @@
-#!/bin/sh
-
-# 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:
-# Build automation for Symbian OS with Raptor
-# Author: Timothy N Murphy
-# 
-#
-
-# Default settings.  You may override these by specifying a setup script
-# as the first commandline argument
-#
-H=$HOME
-export H
-export EPOCROOT="$H/baselineos"
-export LOGBASEDIR=~/public_html/buildlogs
-export BUILDROOT="$H/baselineos"
-export SOURCEROOT="$H/baselineos/fsupdate"
-export SYSDEF="$H/baselineos/system_definition_fsupdate.xml"
-export PREEXPORTSYSDEF="$SBS_HOME/test/envelope/preexport.xml"
-export PLATFORMS="-c armv5"
-export PARALLEL=46
-export SYNCSBSSOURCE=""
-export UNSPLITDIRS="$SBS_HOME/unsplitdirs.py"
-
-# Do we want to attempt to build a ROM?
-export DOROMBUILD=""
-export ROMFILLIN_EPOCROOT=$BUILDROOT/rom_fillin
-#  We need to specify the OBY file (must be generated on windows)
-export ROMOBYFILE="$BUILDROOT/h4hrp_001.techview.oby" 
-
-# Do you have server that runs evalid automatically?
-export SENDTOEVALIDSERVER=""
-#  The following should be mounted:
-export EVALIDSERVERMOUNT="/mnt/evalidserver"
-export USERBUILDID=""
-
-
-# Allow overrides to this default config
-if [ ! -z $1 ]; then 
-	if [ -f "$1" ]; then
-		. $1
-	else
-		echo "You must supply a build type as the first parameter - this should be a setup script"
-		exit 1
-	fi
-fi
-
-
-genstats() { 
-if [ "$1.stats"  -ot "$1.log" ]; then
-python "$SBS_HOME/bin/buildstats.py"  "$1.log" >  "$1.stats" && 
-#python "$SBS_HOME/bin/failedstats.py" -m  "$1.log" >  "$1.failed"; 
-(
-	cd $EPOCROOT/epoc32 && find "release" > "$1.release_files" && find "build" > "$1.build_files" && find include > "$1.include_files"
-)
-fi;
-}
-
-cd $BUILDROOT
-
-
-# Don't edit the rest:
-###################################################
-export KEY=`date +%d_%m_%y`
-export DAILYDIR="$LOGBASEDIR/$KEY"
-
-export BUILDNAME="`basename \"$SYSDEF\" | sed 's#\.[^.][^.]*$##'`"
-if [ ! -z "$USERBUILDID" ]; then
-	BUILDNAME="$USERBUILDID-$BUILDNAME"
-fi
-export LOGNAME="${BUILDNAME}_${KEY}"
-
-for BUILDNUM in {1..50}; do
-	if [ ! -d "$DAILYDIR/$BUILDNUM" ]; then
-		break
-	fi
-	if [ -z "`echo $DAILYDIR/$BUILDNUM/*_BUILDNUM.log*`" ]; then
-		break
-	fi
-done
-
-OUTDIR="$DAILYDIR/$BUILDNUM"
-export TESTLOG="$OUTDIR/test.log"
-
-# make the day's directory
-mkdir -p "$OUTDIR"
-
-echo "testrun: $TESTLOG, build $BUILDNUM of the day:"
-echo '<testrun>' > "$TESTLOG"
-
-echo "Parallel: $PARALLEL"
-(
-echo "<test type='performance' name='speedtest' >"
-echo "	<parameters parallel='$PARALLEL' start='`date`' />"
-echo "	<logfile>$DAILYDIR/$BUILDNUM/${LOGNAME}_$BUILDNUM.log</logfile>"
-MAKEFILE=$EPOCROOT/epoc32/build/Makefile
-echo ""
-
-TIMELOG="$OUTDIR/${LOGNAME}_$BUILDNUM.time"
-
-echo "	<build number='$BUILDNUM' of='$KEY' output='$OUTDIR'><![CDATA["
-if [ ! -d "$OUTDIR" ]; then
-	mkdir -p "$OUTDIR" || exit 1
-fi
-set -x
-
-(
-if [ ! -z "$SYNCSBSSOURCE" ]; then
-	echo "Checking out Raptor source to $SBS_HOME"
-	p4 -u timothymurphy sync $SBS_HOME/...
-else
-	echo "NOT Checking out Raptor source"
-fi
-chmod a+x $SBS_HOME/bin/* # ensure permissions were set
-)
-
-
-# Make sure that our "stop signal" is clear
-SIGNALTOSTOPFILE="$OUTDIR/${LOGNAME}_$BUILDNUM.stop"
-rm -f "$SIGNALTOSTOPFILE"
-
-
-echo "EPOCROOT is $EPOCROOT"
-export PATH=$EPOCROOT/epoc32/tools:$PATH
-
-(
-echo "Annihilating epoc32 tree(s)"
-# wipe the epoc32 directory first
-chmod -R u+rw "$EPOCROOT/epoc32" &&
-rm -rf "$EPOCROOT/epoc32" &&
-echo "epoc32 tree withered" 
-) 
-(
-# unzip the pre-prepared epoc32 trees
-cd $EPOCROOT && 	
-(
-	set -x
-	unzip -o $BUILDROOT/epoc32.zip  | grep "epoc32/" | sed 's#.* \(epoc32/.*\)#\1#' |  xargs -n 1 --replace bash -c "if [ -f '{}' ]; then touch '{}'; fi" && 
-	unzip -o $BUILDROOT/variant.zip  | grep "epoc32/" | sed 's#.* \(epoc32/.*\)#\1#' |  xargs -n 1 --replace bash -c "if [ -f '{}' ]; then touch '{}'; fi" &&
-	set +x
-) > "$OUTDIR/unzip" &&
-chmod -R u+rw "$EPOCROOT/epoc32" &&
-echo "unzipped skeleton epoc32 tree" 
-)
-
-
-# (re)Initialise the cluster if required.
-(
-if [ ! -z "$PARALLEL" ]; then
-	echo "Setting up cluster"
-	echo "Parallel: $PARALLEL"
-	set -x
-	echo -e "halt\n" | pvm >/dev/null
-	echo -e "quit\n" | pvm $BUILDROOT/pvmhosts.$PARALLEL >/dev/null
-	set +x
-else
-	echo "Parallel: 0 - no cluster setup"
-	set -x
-	echo -e "halt\n" | pvm >/dev/null
-	set +x
-fi
-)
-
-
-set +x
-echo "Prepping makefiles"
-(
-	echo "<times>\n"
-	export TIMEFORMAT="<time stage='prepmake'>%3R</time>\n"
-	time $SBS_HOME/bin/sbs -d -k -s "$SYSDEF" -a "$SOURCEROOT" $PLATFORMS -n > $OUTDIR/${LOGNAME}_$BUILDNUM.meta 2>&1 
-	#time cp performance_Makefile $MAKEFILE
-)  > "$TIMELOG" 2>&1
-echo "Running Make"
-(
-	# The build process
-	export TIMEFORMAT="<time stage='make' parallel='$PARALLEL'>%3R</time>\n"
-
-	time /opt/symbian/make-pvm-381/pvmgmake -j$PARALLEL -k -f $MAKEFILE  > "$OUTDIR/${LOGNAME}_$BUILDNUM.log"  2>&1 
-	touch "$SIGNALTOSTOPFILE"
-	echo "</times>\n"
-) >> "$TIMELOG" 2>&1 & 
-(
-	# Concurrent process to continuously update statistics
-	echo ""
-
-	while [ 1 -eq 1 ]; do
-		sleep 20 
-		echo -n "."
-
-		if [ -e "$SIGNALTOSTOPFILE" ]; then
-			rm -f "$SIGNALTOSTOPFILE"
-			break
-		fi
-	done
-	echo ""
-)
-#set +x
-#genstats "$OUTDIR/${LOGNAME}_$BUILDNUM"
-(
-	echo "UNSPLITTING DIRECTORIES"
-        set -x
-        cd $EPOCROOT/epoc32 &&
-        python $UNSPLITDIRS -l . &&
-        set +x
-
-) && (
-	if [ ! -z "$DOROMBUILD" ]; then
-		echo "Building ROM"
-		set -x
-		cd $EPOCROOT &&
-        	unzip -o $BUILDROOT/data.zip >/dev/null &&
-		python $BUILDROOT/oby_tolinux.py < "$ROMOBYFILE" >PROCESSED_H4HRP_001.TECHVIEW.OBY
-		$EPOCROOT/epoc32/tools/rombuild -type-safe-link PROCESSED_H4HRP_001.TECHVIEW.OBY
-		cp
-		set +x
-	else
-		echo "NOT Building ROM"
-	fi
-)
-
-(
-	if [ ! -z "$SENDTOEVALIDSERVER" ]; then
-        	echo "Sending epoc32/release and epoc32/data to the evalidserver"
-		set -x
-		ZIPFILE="$DAILYDIR/$BUILDNUM/${LOGNAME}_$BUILDNUM.zip"
-		cd $EPOCROOT &&
-		find epoc32/release epoc32/data | zip "$ZIPFILE" -@ >/dev/null 2>&1 &&
-		cp "$ZIPFILE" /mnt/evalidserver 
-		set +x
-	else
-        	echo "NOT sending epoc32/release and epoc32/data to the evalidserver"
-	fi
-)
-
-# Zip the logs - note that test.log should not be zipped since the output from the zip goes into it
-(
-	echo "Zipping logs..."
-	set -x
-	cd $OUTDIR &&
-	zip ${LOGNAME}_${BUILDNUM}_logs.zip *.time *.meta *.log *.preexport -x test.log
-	set +x
-)
-
-
-echo "	]]></build>"
-echo "</test>"
-) >> "$TESTLOG" 2>&1
-
-BUILDNUM=$[ $BUILDNUM + 1 ]
-# use a new output directory
-echo -e "<testrun_stat endtime='`date`'\n />" >> "$TESTLOG"
-echo "</testrun>" >> "$TESTLOG"
+#!/bin/sh
+
+# 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:
+# Build automation for Symbian OS with Raptor
+# Author: Timothy N Murphy
+# 
+#
+
+# Default settings.  You may override these by specifying a setup script
+# as the first commandline argument
+#
+H=$HOME
+export H
+export EPOCROOT="$H/baselineos"
+export LOGBASEDIR=~/public_html/buildlogs
+export BUILDROOT="$H/baselineos"
+export SOURCEROOT="$H/baselineos/fsupdate"
+export SYSDEF="$H/baselineos/system_definition_fsupdate.xml"
+export PREEXPORTSYSDEF="$SBS_HOME/test/envelope/preexport.xml"
+export PLATFORMS="-c armv5"
+export PARALLEL=46
+export SYNCSBSSOURCE=""
+export UNSPLITDIRS="$SBS_HOME/unsplitdirs.py"
+
+# Do we want to attempt to build a ROM?
+export DOROMBUILD=""
+export ROMFILLIN_EPOCROOT=$BUILDROOT/rom_fillin
+#  We need to specify the OBY file (must be generated on windows)
+export ROMOBYFILE="$BUILDROOT/h4hrp_001.techview.oby" 
+
+# Do you have server that runs evalid automatically?
+export SENDTOEVALIDSERVER=""
+#  The following should be mounted:
+export EVALIDSERVERMOUNT="/mnt/evalidserver"
+export USERBUILDID=""
+
+
+# Allow overrides to this default config
+if [ ! -z $1 ]; then 
+	if [ -f "$1" ]; then
+		. $1
+	else
+		echo "You must supply a build type as the first parameter - this should be a setup script"
+		exit 1
+	fi
+fi
+
+
+genstats() { 
+if [ "$1.stats"  -ot "$1.log" ]; then
+python "$SBS_HOME/bin/buildstats.py"  "$1.log" >  "$1.stats" && 
+#python "$SBS_HOME/bin/failedstats.py" -m  "$1.log" >  "$1.failed"; 
+(
+	cd $EPOCROOT/epoc32 && find "release" > "$1.release_files" && find "build" > "$1.build_files" && find include > "$1.include_files"
+)
+fi;
+}
+
+cd $BUILDROOT
+
+
+# Don't edit the rest:
+###################################################
+export KEY=`date +%d_%m_%y`
+export DAILYDIR="$LOGBASEDIR/$KEY"
+
+export BUILDNAME="`basename \"$SYSDEF\" | sed 's#\.[^.][^.]*$##'`"
+if [ ! -z "$USERBUILDID" ]; then
+	BUILDNAME="$USERBUILDID-$BUILDNAME"
+fi
+export LOGNAME="${BUILDNAME}_${KEY}"
+
+for BUILDNUM in {1..50}; do
+	if [ ! -d "$DAILYDIR/$BUILDNUM" ]; then
+		break
+	fi
+	if [ -z "`echo $DAILYDIR/$BUILDNUM/*_BUILDNUM.log*`" ]; then
+		break
+	fi
+done
+
+OUTDIR="$DAILYDIR/$BUILDNUM"
+export TESTLOG="$OUTDIR/test.log"
+
+# make the day's directory
+mkdir -p "$OUTDIR"
+
+echo "testrun: $TESTLOG, build $BUILDNUM of the day:"
+echo '<testrun>' > "$TESTLOG"
+
+echo "Parallel: $PARALLEL"
+(
+echo "<test type='performance' name='speedtest' >"
+echo "	<parameters parallel='$PARALLEL' start='`date`' />"
+echo "	<logfile>$DAILYDIR/$BUILDNUM/${LOGNAME}_$BUILDNUM.log</logfile>"
+MAKEFILE=$EPOCROOT/epoc32/build/Makefile
+echo ""
+
+TIMELOG="$OUTDIR/${LOGNAME}_$BUILDNUM.time"
+
+echo "	<build number='$BUILDNUM' of='$KEY' output='$OUTDIR'><![CDATA["
+if [ ! -d "$OUTDIR" ]; then
+	mkdir -p "$OUTDIR" || exit 1
+fi
+set -x
+
+(
+if [ ! -z "$SYNCSBSSOURCE" ]; then
+	echo "Checking out Raptor source to $SBS_HOME"
+	p4 -u timothymurphy sync $SBS_HOME/...
+else
+	echo "NOT Checking out Raptor source"
+fi
+chmod a+x $SBS_HOME/bin/* # ensure permissions were set
+)
+
+
+# Make sure that our "stop signal" is clear
+SIGNALTOSTOPFILE="$OUTDIR/${LOGNAME}_$BUILDNUM.stop"
+rm -f "$SIGNALTOSTOPFILE"
+
+
+echo "EPOCROOT is $EPOCROOT"
+export PATH=$EPOCROOT/epoc32/tools:$PATH
+
+(
+echo "Annihilating epoc32 tree(s)"
+# wipe the epoc32 directory first
+chmod -R u+rw "$EPOCROOT/epoc32" &&
+rm -rf "$EPOCROOT/epoc32" &&
+echo "epoc32 tree withered" 
+) 
+(
+# unzip the pre-prepared epoc32 trees
+cd $EPOCROOT && 	
+(
+	set -x
+	unzip -o $BUILDROOT/epoc32.zip  | grep "epoc32/" | sed 's#.* \(epoc32/.*\)#\1#' |  xargs -n 1 --replace bash -c "if [ -f '{}' ]; then touch '{}'; fi" && 
+	unzip -o $BUILDROOT/variant.zip  | grep "epoc32/" | sed 's#.* \(epoc32/.*\)#\1#' |  xargs -n 1 --replace bash -c "if [ -f '{}' ]; then touch '{}'; fi" &&
+	set +x
+) > "$OUTDIR/unzip" &&
+chmod -R u+rw "$EPOCROOT/epoc32" &&
+echo "unzipped skeleton epoc32 tree" 
+)
+
+
+# (re)Initialise the cluster if required.
+(
+if [ ! -z "$PARALLEL" ]; then
+	echo "Setting up cluster"
+	echo "Parallel: $PARALLEL"
+	set -x
+	echo -e "halt\n" | pvm >/dev/null
+	echo -e "quit\n" | pvm $BUILDROOT/pvmhosts.$PARALLEL >/dev/null
+	set +x
+else
+	echo "Parallel: 0 - no cluster setup"
+	set -x
+	echo -e "halt\n" | pvm >/dev/null
+	set +x
+fi
+)
+
+
+set +x
+echo "Prepping makefiles"
+(
+	echo "<times>\n"
+	export TIMEFORMAT="<time stage='prepmake'>%3R</time>\n"
+	time $SBS_HOME/bin/sbs -d -k -s "$SYSDEF" -a "$SOURCEROOT" $PLATFORMS -n > $OUTDIR/${LOGNAME}_$BUILDNUM.meta 2>&1 
+	#time cp performance_Makefile $MAKEFILE
+)  > "$TIMELOG" 2>&1
+echo "Running Make"
+(
+	# The build process
+	export TIMEFORMAT="<time stage='make' parallel='$PARALLEL'>%3R</time>\n"
+
+	time /opt/symbian/make-pvm-381/pvmgmake -j$PARALLEL -k -f $MAKEFILE  > "$OUTDIR/${LOGNAME}_$BUILDNUM.log"  2>&1 
+	touch "$SIGNALTOSTOPFILE"
+	echo "</times>\n"
+) >> "$TIMELOG" 2>&1 & 
+(
+	# Concurrent process to continuously update statistics
+	echo ""
+
+	while [ 1 -eq 1 ]; do
+		sleep 20 
+		echo -n "."
+
+		if [ -e "$SIGNALTOSTOPFILE" ]; then
+			rm -f "$SIGNALTOSTOPFILE"
+			break
+		fi
+	done
+	echo ""
+)
+#set +x
+#genstats "$OUTDIR/${LOGNAME}_$BUILDNUM"
+(
+	echo "UNSPLITTING DIRECTORIES"
+        set -x
+        cd $EPOCROOT/epoc32 &&
+        python $UNSPLITDIRS -l . &&
+        set +x
+
+) && (
+	if [ ! -z "$DOROMBUILD" ]; then
+		echo "Building ROM"
+		set -x
+		cd $EPOCROOT &&
+        	unzip -o $BUILDROOT/data.zip >/dev/null &&
+		python $BUILDROOT/oby_tolinux.py < "$ROMOBYFILE" >PROCESSED_H4HRP_001.TECHVIEW.OBY
+		$EPOCROOT/epoc32/tools/rombuild -type-safe-link PROCESSED_H4HRP_001.TECHVIEW.OBY
+		cp
+		set +x
+	else
+		echo "NOT Building ROM"
+	fi
+)
+
+(
+	if [ ! -z "$SENDTOEVALIDSERVER" ]; then
+        	echo "Sending epoc32/release and epoc32/data to the evalidserver"
+		set -x
+		ZIPFILE="$DAILYDIR/$BUILDNUM/${LOGNAME}_$BUILDNUM.zip"
+		cd $EPOCROOT &&
+		find epoc32/release epoc32/data | zip "$ZIPFILE" -@ >/dev/null 2>&1 &&
+		cp "$ZIPFILE" /mnt/evalidserver 
+		set +x
+	else
+        	echo "NOT sending epoc32/release and epoc32/data to the evalidserver"
+	fi
+)
+
+# Zip the logs - note that test.log should not be zipped since the output from the zip goes into it
+(
+	echo "Zipping logs..."
+	set -x
+	cd $OUTDIR &&
+	zip ${LOGNAME}_${BUILDNUM}_logs.zip *.time *.meta *.log *.preexport -x test.log
+	set +x
+)
+
+
+echo "	]]></build>"
+echo "</test>"
+) >> "$TESTLOG" 2>&1
+
+BUILDNUM=$[ $BUILDNUM + 1 ]
+# use a new output directory
+echo -e "<testrun_stat endtime='`date`'\n />" >> "$TESTLOG"
+echo "</testrun>" >> "$TESTLOG"
--- a/sbsv2/raptor/bin/raptorlog.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/raptorlog.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,71 +1,71 @@
-#
-# 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: 
-#
-
-	Raptor log parsing utilities.
-
-	Line-by-line based log reporting.
-"""
-
-import re
-
-
-class LogItem(object):
-	keep = False
-	def __init__(self, name, pattern, keep=False, subpattern=None):
-		self.name = name
-		self.matcher = re.compile(pattern, re.I)
-		self.count = 0
-
-		if subpattern:
-			self.subpattern = re.compile(subpattern,re.I)
-		else:
-			self.subpattern = None
-
-		if keep and LogItem.keep:
-			self.keep = {}
-		else:
-			self.keep = None
-
-		self.subpatterncount = 0
-
-	def xml(self):
-		xml = "<logitem name='%s' count='%i' subpatterncount='%i' " % ( self.name, self.count,  self.subpatterncount)
-		if self.keep == None:
-			return xml + " />"
-
-		xml += ">\n"
-
-		index = self.keep.keys()
-		index.sort(cmp=lambda y,x: self.keep[x] - self.keep[y])
-		for i in index:
-			xml += "<match count='" + str(self.keep[i]) +"'><![CDATA[\n" + i + "]]></match>\n"
-		
-		return xml + "</logitem>"
-
-	def match(self, line):
-		result = self.matcher.search(line)
-		if result != None:
-			if self.keep != None:
-				try:
-					self.keep[result.group()] += 1
-				except:
-					self.keep[result.group()] = 1
-			if self.subpattern != None:
-				self.subpatterncount += len(self.subpattern.findall(line))
-				for i in self.subpattern.findall(line):
-					print i
-			self.count += 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: 
+#
+
+	Raptor log parsing utilities.
+
+	Line-by-line based log reporting.
+"""
+
+import re
+
+
+class LogItem(object):
+	keep = False
+	def __init__(self, name, pattern, keep=False, subpattern=None):
+		self.name = name
+		self.matcher = re.compile(pattern, re.I)
+		self.count = 0
+
+		if subpattern:
+			self.subpattern = re.compile(subpattern,re.I)
+		else:
+			self.subpattern = None
+
+		if keep and LogItem.keep:
+			self.keep = {}
+		else:
+			self.keep = None
+
+		self.subpatterncount = 0
+
+	def xml(self):
+		xml = "<logitem name='%s' count='%i' subpatterncount='%i' " % ( self.name, self.count,  self.subpatterncount)
+		if self.keep == None:
+			return xml + " />"
+
+		xml += ">\n"
+
+		index = self.keep.keys()
+		index.sort(cmp=lambda y,x: self.keep[x] - self.keep[y])
+		for i in index:
+			xml += "<match count='" + str(self.keep[i]) +"'><![CDATA[\n" + i + "]]></match>\n"
+		
+		return xml + "</logitem>"
+
+	def match(self, line):
+		result = self.matcher.search(line)
+		if result != None:
+			if self.keep != None:
+				try:
+					self.keep[result.group()] += 1
+				except:
+					self.keep[result.group()] = 1
+			if self.subpattern != None:
+				self.subpatterncount += len(self.subpattern.findall(line))
+				for i in self.subpattern.findall(line):
+					print i
+			self.count += 1
+
--- a/sbsv2/raptor/bin/readme.txt	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/readme.txt	Wed Jun 23 16:56:47 2010 +0800
@@ -1,32 +1,32 @@
-The distribution of the file is based on the follwing article ID:326922 Rev.5 from Microsoft Knowledge Base.
-
-http://support.microsoft.com/kb/326922
-
-
-Article ID: 326922 - Last Review: March 19, 2008 - Revision: 5.0
-Redistribution of the shared C runtime component in Visual C++
-
-
-SUMMARY
-
-When you build an application in Microsoft Visual Studio, and the application uses the C run-time libraries (CRT), distribute the appropriate CRT DLL from the following list with your application:
-
-    * Msvcr90.dll for Microsoft Visual C++ 2008
-    * Msvcr80.dll for Microsoft Visual C++ 2005
-    * Msvcr71.dll for Microsoft Visual C++ .NET 2003 with the Microsoft .NET Framework 1.1
-    * Msvcr70.dll for Microsoft Visual C++ .NET 2002 with the Microsoft .NET Framework 1.0
-
-For Msvcr70.dll or for Msvcr71.dll, you should install the CRT DLL into your application program files directory. You should not install these files into the Windows system directories. For Msvcr80.dll and for Msvcr90.dll, you should install the CRT as Windows side-by-side assemblies.
-
-MORE INFORMATION
-
-The shared CRT DLL has been distributed by Microsoft in the past as a shared system component. This may cause problems when you run applications that are linked to a different version of the CRT on computers that do not have the correct versions of the CRT DLL installed. This is commonly referred to as the "DLL Conflict" problem.
-
-To address this issue, the CRT DLL is no longer considered a system file, therefore, distribute the CRT DLL with any application that relies on it. Because it is no longer a system component, install it in your applications Program Files directory with other application-specific code. This prevents your application from using other versions of the CRT library that may be installed on the system paths.
-
-Visual C++ .NET 2003 or Visual C++ .NET 2002 installs the CRT DLL in the System32 directory on a development system. This is installed as a convenience for the developer. Otherwise, all projects that are built with Visual C++ that link with the shared CRT require a copy of the DLL in the build directory for debugging and execution. Visual C++ 2005 and Visual C++ 2008 install the CRT DLL as a Windows side-by-side assembly on Windows XP and later operating systems. Windows 2000 does not support side-by-side assemblies. On Windows 2000, the CRT DLL is installed in the System32 directory.
-
-When you distribute applications that require the Shared CRT library in the CRT DLL, we recommend that you use the CRT.msm merge module that is included with Visual C++ instead of directly distributing the DLL file.
-
-Windows side-by-side assemblies
-Msvcr80.dll with Visual C++ 2005 and Msvcr90.dll with Visual C++ 2008 are redistributed as Windows side-by-side assemblies except on Windows 2000. You should install these versions of the CRT on target computers by running the Vcredist_x86.exe application that is included with Visual Studio. There are installers for the x64 and IA-64 platforms also. Alternatively, you can use the CRT msm merge module that is supplied with Visual Studio to package the CRT installer into your own setup application. This will make the CRT available as a shared assembly to all applications because it is installed in the \windows\winsxs directory on supported operating systems. 
+The distribution of the file is based on the follwing article ID:326922 Rev.5 from Microsoft Knowledge Base.
+
+http://support.microsoft.com/kb/326922
+
+
+Article ID: 326922 - Last Review: March 19, 2008 - Revision: 5.0
+Redistribution of the shared C runtime component in Visual C++
+
+
+SUMMARY
+
+When you build an application in Microsoft Visual Studio, and the application uses the C run-time libraries (CRT), distribute the appropriate CRT DLL from the following list with your application:
+
+    * Msvcr90.dll for Microsoft Visual C++ 2008
+    * Msvcr80.dll for Microsoft Visual C++ 2005
+    * Msvcr71.dll for Microsoft Visual C++ .NET 2003 with the Microsoft .NET Framework 1.1
+    * Msvcr70.dll for Microsoft Visual C++ .NET 2002 with the Microsoft .NET Framework 1.0
+
+For Msvcr70.dll or for Msvcr71.dll, you should install the CRT DLL into your application program files directory. You should not install these files into the Windows system directories. For Msvcr80.dll and for Msvcr90.dll, you should install the CRT as Windows side-by-side assemblies.
+
+MORE INFORMATION
+
+The shared CRT DLL has been distributed by Microsoft in the past as a shared system component. This may cause problems when you run applications that are linked to a different version of the CRT on computers that do not have the correct versions of the CRT DLL installed. This is commonly referred to as the "DLL Conflict" problem.
+
+To address this issue, the CRT DLL is no longer considered a system file, therefore, distribute the CRT DLL with any application that relies on it. Because it is no longer a system component, install it in your applications Program Files directory with other application-specific code. This prevents your application from using other versions of the CRT library that may be installed on the system paths.
+
+Visual C++ .NET 2003 or Visual C++ .NET 2002 installs the CRT DLL in the System32 directory on a development system. This is installed as a convenience for the developer. Otherwise, all projects that are built with Visual C++ that link with the shared CRT require a copy of the DLL in the build directory for debugging and execution. Visual C++ 2005 and Visual C++ 2008 install the CRT DLL as a Windows side-by-side assembly on Windows XP and later operating systems. Windows 2000 does not support side-by-side assemblies. On Windows 2000, the CRT DLL is installed in the System32 directory.
+
+When you distribute applications that require the Shared CRT library in the CRT DLL, we recommend that you use the CRT.msm merge module that is included with Visual C++ instead of directly distributing the DLL file.
+
+Windows side-by-side assemblies
+Msvcr80.dll with Visual C++ 2005 and Msvcr90.dll with Visual C++ 2008 are redistributed as Windows side-by-side assemblies except on Windows 2000. You should install these versions of the CRT on target computers by running the Vcredist_x86.exe application that is included with Visual Studio. There are installers for the x64 and IA-64 platforms also. Alternatively, you can use the CRT msm merge module that is supplied with Visual Studio to package the CRT installer into your own setup application. This will make the CRT available as a shared assembly to all applications because it is installed in the \windows\winsxs directory on supported operating systems. 
--- a/sbsv2/raptor/bin/sbs	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/sbs	Wed Jun 23 16:56:47 2010 +0800
@@ -1,5 +1,5 @@
 #!/bin/bash
-# Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
+# 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"
@@ -17,7 +17,7 @@
 #
 
 # If SBS_HOME is not set in the environment then work it out
-# from the path to this batch file
+# from the path to this script
 if [ -z "$SBS_HOME" ] ; then
 	temp=$0
 	SBS_HOME=$(cd ${temp%/*} && echo $PWD)
@@ -62,31 +62,47 @@
 fi
 
 if [ "$OSTYPE" == "cygwin" ]; then
-
-	SBS_HOME=${SBS_HOME//\\//}
-
 	__MINGW__=${SBS_MINGW:-$SBS_HOME/$HOSTPLATFORM_DIR/mingw}
 	__CYGWIN__=${SBS_CYGWIN:-$SBS_HOME/$HOSTPLATFORM_DIR/cygwin}
-	__PYTHON__=${SBS_PYTHON:-$SBS_HOME/$HOSTPLATFORM_DIR/python252/python.exe}
 
-    # Command for unifying path strings. For example, "c:\some\path" and
-    # "/cygdrive/c/some/path" will both be converted into "c:/some/path".
+	# Command for unifying path strings. For example, "c:\some\path" and
+	# "/cygdrive/c/some/path" will both be converted into "c:/some/path".
 	u="$__CYGWIN__/bin/cygpath.exe -m"
-
+	
+	SBS_HOME=${SBS_HOME//\\//}
+	export SBS_HOME=$($u "$SBS_HOME")
+	
 	__MINGW__=$($u "$__MINGW__")
 	__CYGWIN__=$($u "$__MINGW__")
-	__PYTHON__=$($u "$__PYTHON__")
-
-	export SBS_HOME=$($u "$SBS_HOME")
-	export EPOCROOT=$($u "$EPOCROOT")
-
 	export PATH=${__MINGW__}/bin:${__CYGWIN__}/bin:$SBS_HOME/$HOSTPLATFORM_DIR/bin:$PATH
 
 	# Tell Cygwin not to map unix security attributes to windows to
 	# prevent raptor from potentially creating read-only files:
 	export CYGWIN='nontsec nosmbntsec'
 
+	# The python and PYTHONPATH used by Raptor are determined by, in order of precedence:
+	#  1. the SBS_PYTHON and SBS_PYTHONPATH environment variables (if set)
+	#  2. the python shipped locally with Raptor (if present)
+	#  3. the python on the system PATH and the PYTHONPATH set in the system environment
+
+	__LOCAL_PYTHON__=$SBS_HOME/win32/python264/python.exe
+
+	if [ -n "$SBS_PYTHON" ]; then
+		__PYTHON__=$SBS_PYTHON
+	elif [ -f "$__LOCAL_PYTHON__" ]; then
+		__PYTHON__=$__LOCAL_PYTHON__
+		export SBS_PYTHON=$__PYTHON__
+		export PYTHONPATH=
+	else
+		__PYTHON__=python.exe
+	fi
+	__PYTHON__=$($u "$__PYTHON__")		
+
+	if [ -n "$SBS_PYTHONPATH" ]; then
+		export PYTHONPATH=$($u "$SBS_PYTHONPATH")
+	fi
 else
+	export PYTHONPATH=${SBS_PYTHONPATH:-$SBS_HOME/$HOSTPLATFORM_DIR/python262/lib}
 	PATH=$SBS_HOME/$HOSTPLATFORM_DIR/python262/bin:$SBS_HOME/$HOSTPLATFORM_DIR/bin:$PATH
 	LD_LIBRARY_PATH=$SBS_HOME/$HOSTPLATFORM_DIR/python262/lib:$SBS_HOME/$HOSTPLATFORM_DIR/bv/lib:$LD_LIBRARY_PATH
 
--- a/sbsv2/raptor/bin/sbs.bat	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/sbs.bat	Wed Jun 23 16:56:47 2010 +0800
@@ -1,60 +1,24 @@
-@rem
-@rem Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
-@rem All rights reserved.
-@rem This component and the accompanying materials are made available
-@rem under the terms of the License "Eclipse Public License v1.0"
-@rem which accompanies this distribution, and is available
-@rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
-@rem
-@rem Initial Contributors:
-@rem Nokia Corporation - initial contribution.
-@rem
-@rem Contributors:
-@rem
-@rem Description: 
-@rem
-
-@SETLOCAL
-@SET HOSTPLATFORM=win 32
-@SET HOSTPLATFORM_DIR=win32
-
-
-@REM Automatically find SBS_HOME if it is not set
-@IF NOT "%SBS_HOME%"==""  goto foundhome
-@SET RAPTORBINDIR=%~dp0
-@SET WD=%cd%
-@cd %RAPTORBINDIR%\..
-@SET SBS_HOME=%cd%
-@cd %WD%
-:foundhome 
-
-@REM Use the python set by the environment if possible
-@SET __PYTHON__=%SBS_PYTHON%
-@IF "%__PYTHON__%"=="" SET __PYTHON__=%SBS_HOME%\win32\python252\python.exe
-
-@REM Use the mingw set by the environment if possible
-@SET __MINGW__=%SBS_MINGW%
-@IF "%__MINGW__%"=="" SET __MINGW__=%SBS_HOME%\win32\mingw
-
-@REM Use the cygwin set by the environment if possible
-@SET __CYGWIN__=%SBS_CYGWIN%
-@IF "%__CYGWIN__%"=="" SET __CYGWIN__=%SBS_HOME%\win32\cygwin
-
-@REM add to the search path
-@SET PATH=%__MINGW__%\bin;%__CYGWIN__%\bin;%SBS_HOME%\win32\bin;%PATH%
-
-@REM Make sure that /tmp is not set incorrectly for sbs
-@umount -u /tmp >NUL  2>NUL
-@mount -u %TEMP% /tmp >NUL 2>NUL
-@umount -u / >NUL  2>NUL
-@mount -u %__CYGWIN__% / >NUL 2>NUL
-
-@REM Tell CYGWIN not to map unix security attributes to windows to
-@REM prevent raptor from potentially creating read-only files:
-@set CYGWIN=nontsec nosmbntsec
-
-@REM Run Raptor with all the arguments.
-@%__PYTHON__% %SBS_HOME%\python\raptor_start.py %*
-
-@ENDLOCAL
-@cmd /c exit /b %ERRORLEVEL%
+@rem
+@rem Copyright (c) 2005-2010 Nokia Corporation and/or its subsidiary(-ies).
+@rem All rights reserved.
+@rem This component and the accompanying materials are made available
+@rem under the terms of the License "Eclipse Public License v1.0"
+@rem which accompanies this distribution, and is available
+@rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+@rem
+@rem Initial Contributors:
+@rem Nokia Corporation - initial contribution.
+@rem
+@rem Contributors:
+@rem
+@rem Description: 
+@rem
+
+@SETLOCAL
+@CALL "%~dp0sbs_env.bat"
+
+@REM Run Raptor with all the arguments.
+@%__PYTHON__% %SBS_HOME%\python\raptor_start.py %*
+
+@ENDLOCAL
+@cmd /c exit /b %ERRORLEVEL%
--- a/sbsv2/raptor/bin/sbsv2cache.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/sbsv2cache.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,311 +1,311 @@
-#
-# 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: 
-# Creates CBR tool compatible cache files from SBSv2 .whatlog variant output
-#
-
-
-import sys
-import os
-from optparse import OptionParser
-import xml.parsers.expat
-import re
-
-
-# Global dictionary of ComponentReleasable objects, keyed on bld.inf file
-BuildReleasables = {}
-
-# Provide a means to form  "traditional" ABLD-like build platforms and variants from SBSv2 configurations
-ConfigMatch = re.compile(r'^(?P<PLATFORM>\w+)_(?P<VARIANT>\w+)(\.((?P<PLATFORMADD>smp)|\w+))*')
-
-WinscwTreeMatch = re.compile(r'[\\|\/]epoc32[\\|\/]release[\\|\/]winscw[\\|\/](?P<VARIANT>(urel|udeb))[\\|\/]', re.IGNORECASE)
-WinDriveMatch = re.compile(r'[A-Za-z]:')
-
-# $self->{abldcache}->{'<bld.inf location> export -what'} =
-# $self->{abldcache}->{'<bld.inf location> <phase> <platform> <variant> -what'} =
-# $self->{abldcache}->{'plats'} =
-CacheGroupPrefix = "$self->{abldcache}->{\'"
-CacheGroupSuffix = "\'} =\n"
-CacheExportGroup = CacheGroupPrefix+"%s export -what"+CacheGroupSuffix
-CacheBuildOutputGroup = CacheGroupPrefix+"%s %s %s %s -what"+CacheGroupSuffix
-CachePlatsGroup = CacheGroupPrefix+"plats"+CacheGroupSuffix
-CacheListOpen = "\t[\n"
-CacheListItem = "\t\'%s\'"
-CacheListItemPair = "\t[\'%s\', \'%s\']"
-CacheListClose = "\t];\n\n"
-
-
-class ComponentReleasable(object):
-	"""Wraps up a bld.inf file in terms of its packagable releasable output."""
-	
-	# If EPOCROOT is set, provide a means to confirm that potentially publishable releasables live under EPOCROOT/epoc32
-	ReleaseTreeMatch = None
-	if os.environ.has_key("EPOCROOT"):
-		ReleaseTreeMatch = re.compile(r'\"*'+os.path.abspath(os.path.join(os.environ["EPOCROOT"],"epoc32")).replace('\\',r'\/').replace('\/',r'[\\|\/]+')+r'[\\|\/]+', re.IGNORECASE)
-		
-	def __init__(self, aBldInfFile, aVerbose=False):
-		self.__BldInfFile = aBldInfFile
-		self.__Verbose = aVerbose
-		self.__Exports = {}
-		self.__BuildOutput = {}
-		self.__Platforms = {}
-		
-	def __IsReleasableItem(self, aBuildItem):
-		if self.ReleaseTreeMatch and self.ReleaseTreeMatch.match(aBuildItem):
-			return True
-		
-		if self.__Verbose:
-			print "Discarding: \'%s\' from \'%s\' as not in the release tree." % (aBuildItem, self.__BldInfFile)
-		return False
-
-	def __StoreBuildItem(self, aPlatform, aVariant, aBuildItem):
-		if not self.__BuildOutput.has_key(aPlatform):
-			self.__BuildOutput[aPlatform] = {}
-			if aPlatform != "ALL":
-				self.__Platforms[aPlatform.upper()] = 1
-		if not self.__BuildOutput[aPlatform].has_key(aVariant):
-			self.__BuildOutput[aPlatform][aVariant] = {}
-		
-		if aBuildItem:
-			self.__BuildOutput[aPlatform][aVariant][aBuildItem] = 1
-		
-	def AddExport(self, aDestination, aSource):
-		if not self.__IsReleasableItem(aDestination):
-			return
-		self.__Exports[aDestination] = aSource
-
-	def AddBuildOutput(self, aBuildItem, aPlatform="ALL", aVariant="ALL"):
-		if not self.__IsReleasableItem(aBuildItem):
-			return
-		if aPlatform != "ALL" and aVariant == "ALL":
-			self.__StoreBuildItem(aPlatform, "urel", aBuildItem)
-			self.__StoreBuildItem(aPlatform, "udeb", aBuildItem)
-		else:
-			self.__StoreBuildItem(aPlatform, aVariant, aBuildItem)
-		
-	def Finalise(self):
-		# Re-visit the stored build items and, in the context of all build platforms having been processed for the
-		# component, copy platform-generic "ALL" output to the concrete build platform outputs
-		if self.__BuildOutput.has_key("ALL"):
-			allItems = self.__BuildOutput["ALL"]["ALL"].keys()		
-			for platform in self.__BuildOutput.keys():
-				for variant in self.__BuildOutput[platform].keys():
-					for allItem in allItems:
-						self.__StoreBuildItem(platform, variant, allItem)			
-			del self.__BuildOutput["ALL"]
-	
-	def GetBldInf(self):
-		return self.__BldInfFile
-
-	def GetExports(self):
-		return self.__Exports
-
-	def GetBuildOutput(self):
-		return self.__BuildOutput
-
-	def GetPlatforms(self):
-		return self.__Platforms
-
-	def HasReleasables(self):
-		return (self.__BuildOutput or self.__Exports)
-							
-
-def error(aMessage):
-	sys.stderr.write("ERROR: sbsv2cache.py : %s\n" % aMessage)
-	sys.exit(1)
-	
-def processReleasableElement(aContext, aName, aValue, aVerbose):
-	bldinf = aContext["bldinf"]
-	mmp = aContext["mmp"]
-	config = aContext["config"]
-
-	platform = ""
-	variant = ""
-	configMatchResults = ConfigMatch.match(config)
-	if configMatchResults:
-		platform = configMatchResults.group('PLATFORM')
-		variant = configMatchResults.group('VARIANT')	
-		if configMatchResults.group('PLATFORMADD'):
-			platform += configMatchResults.group('PLATFORMADD')
-	
-	if not BuildReleasables.has_key(bldinf):
-		BuildReleasables[bldinf] = ComponentReleasable(bldinf, aVerbose)
-	
-	componentReleasable = BuildReleasables[bldinf]
-	
-	if aName == "export" :
-		componentReleasable.AddExport(aValue["destination"], aValue["source"])
-	elif aName == "member":
-		componentReleasable.AddExport(aValue.keys()[0], aContext["zipfile"])
-	elif aName == "build":
-		componentReleasable.AddBuildOutput(aValue.keys()[0], platform, variant)
-	elif aName == "resource" or aName == "bitmap":
-		item = aValue.keys()[0]
-		# Identify winscw urel/udeb specific resources, and store accordingly
-		winscwTreeMatchResult = WinscwTreeMatch.search(item)
-		if platform == "winscw" and winscwTreeMatchResult:
-			componentReleasable.AddBuildOutput(item, platform, winscwTreeMatchResult.group("VARIANT").lower())
-		else:
-			componentReleasable.AddBuildOutput(item, platform)
-	elif aName == "stringtable":
-		componentReleasable.AddBuildOutput(aValue.keys()[0])			
-
-def parseLog(aLog, aVerbose):
-	if not os.path.exists(aLog):
-		error("Log file %s does not exist." % aLog)
-		
-	parser = xml.parsers.expat.ParserCreate()
-	parser.buffer_text = True
-	
-	elementContext = {}
-	currentElement = []
-		
-	def start_element(name, attributes):
-		if name == "whatlog" or name == "archive":
-			elementContext.update(attributes)
-		elif elementContext.has_key("bldinf"):
-			if name == "export":
-				# Exports are all attributes, so deal with them directly
-				processReleasableElement(elementContext, name, attributes, aVerbose)
-			else:
-				# Other elements wrap values, get these later
-				currentElement.append(name)
-						
-	def end_element(name):
-		if name == "whatlog":
-			elementContext.clear()
-		elif name == "archive":
-			del elementContext["zipfile"]
-	
-	def char_data(data):
-		if elementContext.has_key("bldinf") and currentElement:
-			processReleasableElement(elementContext, currentElement.pop(), {str(data):1}, aVerbose)
-	
-	parser.StartElementHandler = start_element
-	parser.EndElementHandler = end_element
-	parser.CharacterDataHandler = char_data
-
-	try:
-		if aVerbose:
-			print "Parsing: " + aLog
-			
-		parser.ParseFile(open(aLog, "r"))
-	except xml.parsers.expat.ExpatError, e:	
-		error("Failure parsing log file \'%s\' (line %s)" % (aLog, e.lineno))
-
-def normFileForCache(aFile):
-	normedFile = WinDriveMatch.sub("",aFile)
-	normedFile = normedFile.replace("/", "\\")
-	normedFile = normedFile.replace("\\", "\\\\")
-	normedFile = normedFile.replace("\\\\\\\\", "\\\\")
-	normedFile = normedFile.replace("\"", "")
-	return normedFile
-	
-def dumpCacheFileList(aCacheFileObject, aItems, aPairs=False):	
-	numItems = len(aItems)
-	suffix = ",\n"
-	
-	aCacheFileObject.write(CacheListOpen)
-	for item in aItems:
-		if aItems.index(item) == numItems-1:
-			suffix = "\n"			
-		if aPairs:
-			aCacheFileObject.write((CacheListItemPair % (normFileForCache(item[0]), normFileForCache(item[1]))) + suffix)
-		else:
-			aCacheFileObject.write((CacheListItem % normFileForCache(item)) + suffix)
-	aCacheFileObject.write(CacheListClose)
-	
-def createCacheFile(aComponentReleasable, aOutputPath, aSourceExports, aVerbose):	
-	if not aComponentReleasable.HasReleasables():
-		return
-	
-	cacheFileDir = os.path.normpath(\
-				os.path.join(aOutputPath, \
-	            WinDriveMatch.sub("",os.path.dirname(aComponentReleasable.GetBldInf())).lstrip(r'/').lstrip(r'\\')))
-	cacheFile = os.path.join(cacheFileDir, "cache")
-	
-	bldInfLoc = WinDriveMatch.sub("",os.path.dirname(aComponentReleasable.GetBldInf())).replace("/", "\\")
-
-	if aVerbose:
-		print "Creating: " + cacheFile
-	
-	if not os.path.exists(cacheFileDir):
-		os.makedirs(cacheFileDir)
-	
-	try:
-		cacheFileObject = open(cacheFile, 'w')
-	
-		exports = aComponentReleasable.GetExports()
-		if exports:
-			cacheFileObject.write(CacheExportGroup % bldInfLoc)
-			if aSourceExports:
-				dumpCacheFileList(cacheFileObject, exports.items(), True)
-			else:
-				dumpCacheFileList(cacheFileObject, exports.keys())
-	
-		buildOutput = aComponentReleasable.GetBuildOutput()		
-		if buildOutput:
-			for plat in buildOutput.keys():
-				# Most cache output is represented as if performed for the "abld target" phase, but tools platforms
-				# are presented as if performed by "abld build", and so must additionally replicate any exports
-				# performed for the component in their variant output
-				phase = "target"
-				additionalOutput = []
-				if plat == "tools" or plat == "tools2":
-					phase = "build"
-					if exports:
-						additionalOutput = exports.keys()
-				
-				for variant in buildOutput[plat].keys():
-					cacheFileObject.write(CacheBuildOutputGroup % (bldInfLoc, phase, plat, variant))
-					dumpCacheFileList(cacheFileObject, buildOutput[plat][variant].keys() + additionalOutput)
-	
-		cacheFileObject.write(CachePlatsGroup)
-		dumpCacheFileList(cacheFileObject, aComponentReleasable.GetPlatforms().keys())
-		
-		cacheFileObject.close()
-	except IOError:
-		error("Failure creating cache file %s." % cacheFile)
-
-
-def main():
-	parser = OptionParser(prog="sbsv2cache.py")
-	parser.add_option("-l", "--log", action="append", dest="logs", help="log file to parse for <whatlog/> wrapped content.")
-	parser.add_option("-o", "--outputpath", action="store", dest="outputpath", help="root location to generate cache files.")
-	parser.add_option("-s", "--sourceexports", action="store_true", default=False, dest="sourceexports", help="generate cache files where each element in the export array is a ['destination', 'source'] array rather than just a 'destination' element.")
-	parser.add_option("-v", "--verbose", action="store_true", default=False, dest="verbose", help="provide more information as things happen.")
-	
-	(options, leftover_args) = parser.parse_args(sys.argv[1:])
-
-	if leftover_args or not options.logs or not options.outputpath:
-		parser.print_help()
-		sys.exit(1)
-		
-	print "sbsv2cache: started"
-	
-	# Parse build logs to populate the BuildReleasables dictionary
-	for log in options.logs:
-		parseLog(os.path.abspath(log), options.verbose)
-	
-	# Finalise components in BuildReleasables and create cache files as we go
-	for component in BuildReleasables.keys():
-		BuildReleasables[component].Finalise()
-		createCacheFile(BuildReleasables[component], os.path.abspath(options.outputpath), options.sourceexports, options.verbose)
-		
-	print "sbsv2cache: finished"
-	
-if __name__ == "__main__":
-	main()
-	
-
+#
+# 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: 
+# Creates CBR tool compatible cache files from SBSv2 .whatlog variant output
+#
+
+
+import sys
+import os
+from optparse import OptionParser
+import xml.parsers.expat
+import re
+
+
+# Global dictionary of ComponentReleasable objects, keyed on bld.inf file
+BuildReleasables = {}
+
+# Provide a means to form  "traditional" ABLD-like build platforms and variants from SBSv2 configurations
+ConfigMatch = re.compile(r'^(?P<PLATFORM>\w+)_(?P<VARIANT>\w+)(\.((?P<PLATFORMADD>smp)|\w+))*')
+
+WinscwTreeMatch = re.compile(r'[\\|\/]epoc32[\\|\/]release[\\|\/]winscw[\\|\/](?P<VARIANT>(urel|udeb))[\\|\/]', re.IGNORECASE)
+WinDriveMatch = re.compile(r'[A-Za-z]:')
+
+# $self->{abldcache}->{'<bld.inf location> export -what'} =
+# $self->{abldcache}->{'<bld.inf location> <phase> <platform> <variant> -what'} =
+# $self->{abldcache}->{'plats'} =
+CacheGroupPrefix = "$self->{abldcache}->{\'"
+CacheGroupSuffix = "\'} =\n"
+CacheExportGroup = CacheGroupPrefix+"%s export -what"+CacheGroupSuffix
+CacheBuildOutputGroup = CacheGroupPrefix+"%s %s %s %s -what"+CacheGroupSuffix
+CachePlatsGroup = CacheGroupPrefix+"plats"+CacheGroupSuffix
+CacheListOpen = "\t[\n"
+CacheListItem = "\t\'%s\'"
+CacheListItemPair = "\t[\'%s\', \'%s\']"
+CacheListClose = "\t];\n\n"
+
+
+class ComponentReleasable(object):
+	"""Wraps up a bld.inf file in terms of its packagable releasable output."""
+	
+	# If EPOCROOT is set, provide a means to confirm that potentially publishable releasables live under EPOCROOT/epoc32
+	ReleaseTreeMatch = None
+	if os.environ.has_key("EPOCROOT"):
+		ReleaseTreeMatch = re.compile(r'\"*'+os.path.abspath(os.path.join(os.environ["EPOCROOT"],"epoc32")).replace('\\',r'\/').replace('\/',r'[\\|\/]+')+r'[\\|\/]+', re.IGNORECASE)
+		
+	def __init__(self, aBldInfFile, aVerbose=False):
+		self.__BldInfFile = aBldInfFile
+		self.__Verbose = aVerbose
+		self.__Exports = {}
+		self.__BuildOutput = {}
+		self.__Platforms = {}
+		
+	def __IsReleasableItem(self, aBuildItem):
+		if self.ReleaseTreeMatch and self.ReleaseTreeMatch.match(aBuildItem):
+			return True
+		
+		if self.__Verbose:
+			print "Discarding: \'%s\' from \'%s\' as not in the release tree." % (aBuildItem, self.__BldInfFile)
+		return False
+
+	def __StoreBuildItem(self, aPlatform, aVariant, aBuildItem):
+		if not self.__BuildOutput.has_key(aPlatform):
+			self.__BuildOutput[aPlatform] = {}
+			if aPlatform != "ALL":
+				self.__Platforms[aPlatform.upper()] = 1
+		if not self.__BuildOutput[aPlatform].has_key(aVariant):
+			self.__BuildOutput[aPlatform][aVariant] = {}
+		
+		if aBuildItem:
+			self.__BuildOutput[aPlatform][aVariant][aBuildItem] = 1
+		
+	def AddExport(self, aDestination, aSource):
+		if not self.__IsReleasableItem(aDestination):
+			return
+		self.__Exports[aDestination] = aSource
+
+	def AddBuildOutput(self, aBuildItem, aPlatform="ALL", aVariant="ALL"):
+		if not self.__IsReleasableItem(aBuildItem):
+			return
+		if aPlatform != "ALL" and aVariant == "ALL":
+			self.__StoreBuildItem(aPlatform, "urel", aBuildItem)
+			self.__StoreBuildItem(aPlatform, "udeb", aBuildItem)
+		else:
+			self.__StoreBuildItem(aPlatform, aVariant, aBuildItem)
+		
+	def Finalise(self):
+		# Re-visit the stored build items and, in the context of all build platforms having been processed for the
+		# component, copy platform-generic "ALL" output to the concrete build platform outputs
+		if self.__BuildOutput.has_key("ALL"):
+			allItems = self.__BuildOutput["ALL"]["ALL"].keys()		
+			for platform in self.__BuildOutput.keys():
+				for variant in self.__BuildOutput[platform].keys():
+					for allItem in allItems:
+						self.__StoreBuildItem(platform, variant, allItem)			
+			del self.__BuildOutput["ALL"]
+	
+	def GetBldInf(self):
+		return self.__BldInfFile
+
+	def GetExports(self):
+		return self.__Exports
+
+	def GetBuildOutput(self):
+		return self.__BuildOutput
+
+	def GetPlatforms(self):
+		return self.__Platforms
+
+	def HasReleasables(self):
+		return (self.__BuildOutput or self.__Exports)
+							
+
+def error(aMessage):
+	sys.stderr.write("ERROR: sbsv2cache.py : %s\n" % aMessage)
+	sys.exit(1)
+	
+def processReleasableElement(aContext, aName, aValue, aVerbose):
+	bldinf = aContext["bldinf"]
+	mmp = aContext["mmp"]
+	config = aContext["config"]
+
+	platform = ""
+	variant = ""
+	configMatchResults = ConfigMatch.match(config)
+	if configMatchResults:
+		platform = configMatchResults.group('PLATFORM')
+		variant = configMatchResults.group('VARIANT')	
+		if configMatchResults.group('PLATFORMADD'):
+			platform += configMatchResults.group('PLATFORMADD')
+	
+	if not BuildReleasables.has_key(bldinf):
+		BuildReleasables[bldinf] = ComponentReleasable(bldinf, aVerbose)
+	
+	componentReleasable = BuildReleasables[bldinf]
+	
+	if aName == "export" :
+		componentReleasable.AddExport(aValue["destination"], aValue["source"])
+	elif aName == "member":
+		componentReleasable.AddExport(aValue.keys()[0], aContext["zipfile"])
+	elif aName == "build":
+		componentReleasable.AddBuildOutput(aValue.keys()[0], platform, variant)
+	elif aName == "resource" or aName == "bitmap":
+		item = aValue.keys()[0]
+		# Identify winscw urel/udeb specific resources, and store accordingly
+		winscwTreeMatchResult = WinscwTreeMatch.search(item)
+		if platform == "winscw" and winscwTreeMatchResult:
+			componentReleasable.AddBuildOutput(item, platform, winscwTreeMatchResult.group("VARIANT").lower())
+		else:
+			componentReleasable.AddBuildOutput(item, platform)
+	elif aName == "stringtable":
+		componentReleasable.AddBuildOutput(aValue.keys()[0])			
+
+def parseLog(aLog, aVerbose):
+	if not os.path.exists(aLog):
+		error("Log file %s does not exist." % aLog)
+		
+	parser = xml.parsers.expat.ParserCreate()
+	parser.buffer_text = True
+	
+	elementContext = {}
+	currentElement = []
+		
+	def start_element(name, attributes):
+		if name == "whatlog" or name == "archive":
+			elementContext.update(attributes)
+		elif elementContext.has_key("bldinf"):
+			if name == "export":
+				# Exports are all attributes, so deal with them directly
+				processReleasableElement(elementContext, name, attributes, aVerbose)
+			else:
+				# Other elements wrap values, get these later
+				currentElement.append(name)
+						
+	def end_element(name):
+		if name == "whatlog":
+			elementContext.clear()
+		elif name == "archive":
+			del elementContext["zipfile"]
+	
+	def char_data(data):
+		if elementContext.has_key("bldinf") and currentElement:
+			processReleasableElement(elementContext, currentElement.pop(), {str(data):1}, aVerbose)
+	
+	parser.StartElementHandler = start_element
+	parser.EndElementHandler = end_element
+	parser.CharacterDataHandler = char_data
+
+	try:
+		if aVerbose:
+			print "Parsing: " + aLog
+			
+		parser.ParseFile(open(aLog, "r"))
+	except xml.parsers.expat.ExpatError, e:	
+		error("Failure parsing log file \'%s\' (line %s)" % (aLog, e.lineno))
+
+def normFileForCache(aFile):
+	normedFile = WinDriveMatch.sub("",aFile)
+	normedFile = normedFile.replace("/", "\\")
+	normedFile = normedFile.replace("\\", "\\\\")
+	normedFile = normedFile.replace("\\\\\\\\", "\\\\")
+	normedFile = normedFile.replace("\"", "")
+	return normedFile
+	
+def dumpCacheFileList(aCacheFileObject, aItems, aPairs=False):	
+	numItems = len(aItems)
+	suffix = ",\n"
+	
+	aCacheFileObject.write(CacheListOpen)
+	for item in aItems:
+		if aItems.index(item) == numItems-1:
+			suffix = "\n"			
+		if aPairs:
+			aCacheFileObject.write((CacheListItemPair % (normFileForCache(item[0]), normFileForCache(item[1]))) + suffix)
+		else:
+			aCacheFileObject.write((CacheListItem % normFileForCache(item)) + suffix)
+	aCacheFileObject.write(CacheListClose)
+	
+def createCacheFile(aComponentReleasable, aOutputPath, aSourceExports, aVerbose):	
+	if not aComponentReleasable.HasReleasables():
+		return
+	
+	cacheFileDir = os.path.normpath(\
+				os.path.join(aOutputPath, \
+	            WinDriveMatch.sub("",os.path.dirname(aComponentReleasable.GetBldInf())).lstrip(r'/').lstrip(r'\\')))
+	cacheFile = os.path.join(cacheFileDir, "cache")
+	
+	bldInfLoc = WinDriveMatch.sub("",os.path.dirname(aComponentReleasable.GetBldInf())).replace("/", "\\")
+
+	if aVerbose:
+		print "Creating: " + cacheFile
+	
+	if not os.path.exists(cacheFileDir):
+		os.makedirs(cacheFileDir)
+	
+	try:
+		cacheFileObject = open(cacheFile, 'w')
+	
+		exports = aComponentReleasable.GetExports()
+		if exports:
+			cacheFileObject.write(CacheExportGroup % bldInfLoc)
+			if aSourceExports:
+				dumpCacheFileList(cacheFileObject, exports.items(), True)
+			else:
+				dumpCacheFileList(cacheFileObject, exports.keys())
+	
+		buildOutput = aComponentReleasable.GetBuildOutput()		
+		if buildOutput:
+			for plat in buildOutput.keys():
+				# Most cache output is represented as if performed for the "abld target" phase, but tools platforms
+				# are presented as if performed by "abld build", and so must additionally replicate any exports
+				# performed for the component in their variant output
+				phase = "target"
+				additionalOutput = []
+				if plat == "tools" or plat == "tools2":
+					phase = "build"
+					if exports:
+						additionalOutput = exports.keys()
+				
+				for variant in buildOutput[plat].keys():
+					cacheFileObject.write(CacheBuildOutputGroup % (bldInfLoc, phase, plat, variant))
+					dumpCacheFileList(cacheFileObject, buildOutput[plat][variant].keys() + additionalOutput)
+	
+		cacheFileObject.write(CachePlatsGroup)
+		dumpCacheFileList(cacheFileObject, aComponentReleasable.GetPlatforms().keys())
+		
+		cacheFileObject.close()
+	except IOError:
+		error("Failure creating cache file %s." % cacheFile)
+
+
+def main():
+	parser = OptionParser(prog="sbsv2cache.py")
+	parser.add_option("-l", "--log", action="append", dest="logs", help="log file to parse for <whatlog/> wrapped content.")
+	parser.add_option("-o", "--outputpath", action="store", dest="outputpath", help="root location to generate cache files.")
+	parser.add_option("-s", "--sourceexports", action="store_true", default=False, dest="sourceexports", help="generate cache files where each element in the export array is a ['destination', 'source'] array rather than just a 'destination' element.")
+	parser.add_option("-v", "--verbose", action="store_true", default=False, dest="verbose", help="provide more information as things happen.")
+	
+	(options, leftover_args) = parser.parse_args(sys.argv[1:])
+
+	if leftover_args or not options.logs or not options.outputpath:
+		parser.print_help()
+		sys.exit(1)
+		
+	print "sbsv2cache: started"
+	
+	# Parse build logs to populate the BuildReleasables dictionary
+	for log in options.logs:
+		parseLog(os.path.abspath(log), options.verbose)
+	
+	# Finalise components in BuildReleasables and create cache files as we go
+	for component in BuildReleasables.keys():
+		BuildReleasables[component].Finalise()
+		createCacheFile(BuildReleasables[component], os.path.abspath(options.outputpath), options.sourceexports, options.verbose)
+		
+	print "sbsv2cache: finished"
+	
+if __name__ == "__main__":
+	main()
+	
+
--- a/sbsv2/raptor/bin/setup_user.sh	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/setup_user.sh	Wed Jun 23 16:56:47 2010 +0800
@@ -1,41 +1,41 @@
-#!/bin/bash
-
-# Add environment settings to user's 
-# .bashrc
-# .bash_profile
-
-# Add a .pvmrc
-
-. `dirname $0`/user.bash_profile
-
-
-echo "Configuring user account $USER for sbsv2 in: $SBS_HOME"
-
-if [ ! -d "$SBS_HOME" ]; then
-	echo "SBS_HOME appears to not be set correctly: $SBS_HOME" 1>&2
-	exit 1
-fi
-
-patchfile()
-{
-echo "Adding '$2' to $1"
-grep -q '# SBS_SETTINGS' "$1"
-if [ $? -eq 0 ]; then 
-	sed "s%.* # SBS_SETTINGS (do not edit this line).*%$2 # SBS_SETTINGS (do not edit this line)%"  "$1" > "$1.sbsv2" &&
-	mv "$1" "$1.orig" &&
-	mv "$1.sbsv2" "$1"
-else
-	cp "$1" "$1.orig" &&
-	echo "$2 # SBS_SETTINGS (do not edit this line)" >> "$1"
-fi
-}
-
-# Patch the bash profile
-patchfile ~/.bash_profile ". $SBS_HOME/bin/user.bash_profile"
-patchfile ~/.bashrc ". $SBS_HOME/bin/user.bashrc"
-
-if [ -f ~/.pvmrc ]; then
-       cp ~/.pvmrc ~/.pvmrc.orig
-fi
-
-cp $SBS_HOME/util/install-linux/linux_pvmrc ~/.pvmrc
+#!/bin/bash
+
+# Add environment settings to user's 
+# .bashrc
+# .bash_profile
+
+# Add a .pvmrc
+
+. `dirname $0`/user.bash_profile
+
+
+echo "Configuring user account $USER for sbsv2 in: $SBS_HOME"
+
+if [ ! -d "$SBS_HOME" ]; then
+	echo "SBS_HOME appears to not be set correctly: $SBS_HOME" 1>&2
+	exit 1
+fi
+
+patchfile()
+{
+echo "Adding '$2' to $1"
+grep -q '# SBS_SETTINGS' "$1"
+if [ $? -eq 0 ]; then 
+	sed "s%.* # SBS_SETTINGS (do not edit this line).*%$2 # SBS_SETTINGS (do not edit this line)%"  "$1" > "$1.sbsv2" &&
+	mv "$1" "$1.orig" &&
+	mv "$1.sbsv2" "$1"
+else
+	cp "$1" "$1.orig" &&
+	echo "$2 # SBS_SETTINGS (do not edit this line)" >> "$1"
+fi
+}
+
+# Patch the bash profile
+patchfile ~/.bash_profile ". $SBS_HOME/bin/user.bash_profile"
+patchfile ~/.bashrc ". $SBS_HOME/bin/user.bashrc"
+
+if [ -f ~/.pvmrc ]; then
+       cp ~/.pvmrc ~/.pvmrc.orig
+fi
+
+cp $SBS_HOME/util/install-linux/linux_pvmrc ~/.pvmrc
--- a/sbsv2/raptor/bin/speedtest_osbuild.sh	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/speedtest_osbuild.sh	Wed Jun 23 16:56:47 2010 +0800
@@ -1,166 +1,166 @@
-#!/bin/sh
-
-# 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:
-# Build automation for Symbian OS with Raptor
-# Author: Timothy N Murphy
-# 
-#
-
-# You can edit these:
-H=/home/tmurphy
-export H
-export EPOCROOT="$H/baselineos"
-export LOGBASEDIR=~/public_html/buildlogs
-export BUILDROOT="$H/baselineos"
-export SOURCEROOT="$H/baselineos/fsupdate"
-export SYSDEF="$H/baselineos/system_definition_fsupdate.xml"
-export PREEXPORTSYSDEF="$SBS_HOME/test/envelope/preexport.xml"
-#export PARALLEL=0
-
-genstats() { 
-if [ "$1.stats"  -ot "$1.log" ]; then
-python "$SBS_HOME/bin/buildstats.py"  "$1.log" >  "$1.stats" && 
-#python "$SBS_HOME/bin/failedstats.py" -m  "$1.log" >  "$1.failed"; 
-(
-	cd $EPOCROOT/epoc32 && find "release" > "$1.release_files" && find "build" > "$1.build_files" && find include > "$1.include_files"
-)
-fi;
-}
-
-cd $BUILDROOT
-
-
-# Don't edit the rest:
-###################################################
-export KEY=`date +%d_%m_%y`
-export DAILYDIR="$LOGBASEDIR/$KEY"
-export BUILDNAME="`basename \"$SYSDEF\" | sed 's#\.[^.][^.]*$##'`"
-export LOGNAME="${BUILDNAME}_${KEY}"
-export PLATFORM=armv5
-export TESTLOG="$DAILYDIR/parallel_speedtest.log"
-
-for BUILDNUM in {1..50}; do
-	if [ ! -d "$DAILYDIR/$BUILDNUM" ]; then
-		break
-	fi
-	if [ ! -f "$DAILYDIR/$BUILDNUM/${LOGNAME}_$BUILDNUM.log" ]; then
-		break
-	fi
-done
-
-# make the day's directory
-mkdir -p "$DAILYDIR"
-
-echo "testrun: $TESTLOG, build $BUILDNUM of the day:"
-echo '<testrun>' > "$TESTLOG"
-
-
-# Loop through different cluster loads
-#for PARALLEL in 52 48 44 40 36 32 28 24 20 16 8 4; do
-for PARALLEL in 44 40 36 32 28 24 20 16 8 4; do
-export PARALLEL  i
-echo "Parallel: $PARALLEL"
-(
-echo "<test type='performance' name='speedtest' >"
-echo "	<parameters parallel='$PARALLEL' start='`date`' />"
-echo "	<logfile>$DAILYDIR/$BUILDNUM/${LOGNAME}_$BUILDNUM.log</logfile>"
-MAKEFILE=$TESTBASE/test$CODEFACTOR.mk
-echo ""
-
-OUTDIR="$DAILYDIR/$BUILDNUM"
-TIMELOG="$OUTDIR/${LOGNAME}_$BUILDNUM.time"
-
-echo "	<build number='$BUILDNUM' of='$KEY' output='$OUTDIR'><![CDATA["
-if [ ! -d "$OUTDIR" ]; then
-	mkdir -p "$OUTDIR" || exit 1
-fi
-set -x
-
-# Make sure that our "stop signal" is clear
-SIGNALTOSTOPFILE="$OUTDIR/${LOGNAME}_$BUILDNUM.stop"
-rm -f "$SIGNALTOSTOPFILE"
-
-
-echo "EPOCROOT is $EPOCROOT"
-export PATH=$EPOCROOT/epoc32/tools:$PATH
-
-(
-echo "Annihilating epoc32 tree(s)"
-# wipe the epoc32 directory first
-chmod -R u+rw "$EPOCROOT/epoc32" &&
-rm -rf "$EPOCROOT/epoc32" &&
-echo "epoc32 tree withered" 
-) 
-(
-# unzip the pre-prepared epoc32 trees
-cd $EPOCROOT && 	
-(
-	unzip -o $BUILDROOT/epoc32.zip  | grep "epoc32/" | sed 's#.* \(epoc32/.*\)#\1#' | xargs touch && 
-	unzip -o $BUILDROOT/variant.zip  | grep "epoc32/" | sed 's#.* \(epoc32/.*\)#\1#' | xargs touch
-) > "$OUTDIR/unzip" &&
-chmod -R u+rw "$EPOCROOT/epoc32" &&
-echo "unzipped skeleton epoc32 tree" 
-) && (
-echo "Pre-export"
-$SBS_HOME/bin/sbs  -d -k -s "$PREEXPORTSYSDEF" -a "$SOURCEROOT" -c $PLATFORM EXPORT > $OUTDIR/${LOGNAME}_$BUILDNUM.preexport 2>&1 || {
-	echo "Pre-export failed";
-	exit 1
-}
-)
-
-echo "Prepping makefiles"
-(
-	echo "<times>\n"
-	export TIMEFORMAT=$'<time stage='prepmake'>%3R</time>\n'
-	time cp performance_Makefile $EPOCROOT/epoc32/build/Makefile
-)  > "$TIMELOG" 2>&1
-
-echo "Running Make"
-(
-	# The build process
-	 export TIMEFORMAT=$'<time stage='make' parallel='$PARALLEL'>%3R</time>\n'
-
-	time /usr/local/raptor/make-pvm-381/pvmgmake -j$PARALLEL --debug=j -k -f $MAKEFILE  > "$OUTDIR/${LOGNAME}_$BUILDNUM.log" 2>&1 
-	touch "$SIGNALTOSTOPFILE"
-	echo "</times>\n"
-) >> "$TIMELOG" 2>&1 & 
-(
-	set +x
-	# Concurrent process to continuously update statistics
-	echo ""
-
-	while [ 1 -eq 1 ]; do
-		sleep 20 
-		echo -n "."
-
-		if [ -e "$SIGNALTOSTOPFILE" ]; then
-			rm -f "$SIGNALTOSTOPFILE"
-			break
-		fi
-	done
-	echo ""
-)
-set +x
-genstats "$OUTDIR/${LOGNAME}_$BUILDNUM"
-
-echo "	]]></build>"
-echo "</test>"
-) >> "$TESTLOG" 2>&1
-
-BUILDNUM=$[ $BUILDNUM + 1 ]
-# use a new output directory
-done # PARALLEL
-echo -e "<testrun_stat endtime='`date`'\n />" >> "$TESTLOG"
-echo "</testrun>" >> "$TESTLOG"
+#!/bin/sh
+
+# 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:
+# Build automation for Symbian OS with Raptor
+# Author: Timothy N Murphy
+# 
+#
+
+# You can edit these:
+H=/home/tmurphy
+export H
+export EPOCROOT="$H/baselineos"
+export LOGBASEDIR=~/public_html/buildlogs
+export BUILDROOT="$H/baselineos"
+export SOURCEROOT="$H/baselineos/fsupdate"
+export SYSDEF="$H/baselineos/system_definition_fsupdate.xml"
+export PREEXPORTSYSDEF="$SBS_HOME/test/envelope/preexport.xml"
+#export PARALLEL=0
+
+genstats() { 
+if [ "$1.stats"  -ot "$1.log" ]; then
+python "$SBS_HOME/bin/buildstats.py"  "$1.log" >  "$1.stats" && 
+#python "$SBS_HOME/bin/failedstats.py" -m  "$1.log" >  "$1.failed"; 
+(
+	cd $EPOCROOT/epoc32 && find "release" > "$1.release_files" && find "build" > "$1.build_files" && find include > "$1.include_files"
+)
+fi;
+}
+
+cd $BUILDROOT
+
+
+# Don't edit the rest:
+###################################################
+export KEY=`date +%d_%m_%y`
+export DAILYDIR="$LOGBASEDIR/$KEY"
+export BUILDNAME="`basename \"$SYSDEF\" | sed 's#\.[^.][^.]*$##'`"
+export LOGNAME="${BUILDNAME}_${KEY}"
+export PLATFORM=armv5
+export TESTLOG="$DAILYDIR/parallel_speedtest.log"
+
+for BUILDNUM in {1..50}; do
+	if [ ! -d "$DAILYDIR/$BUILDNUM" ]; then
+		break
+	fi
+	if [ ! -f "$DAILYDIR/$BUILDNUM/${LOGNAME}_$BUILDNUM.log" ]; then
+		break
+	fi
+done
+
+# make the day's directory
+mkdir -p "$DAILYDIR"
+
+echo "testrun: $TESTLOG, build $BUILDNUM of the day:"
+echo '<testrun>' > "$TESTLOG"
+
+
+# Loop through different cluster loads
+#for PARALLEL in 52 48 44 40 36 32 28 24 20 16 8 4; do
+for PARALLEL in 44 40 36 32 28 24 20 16 8 4; do
+export PARALLEL  i
+echo "Parallel: $PARALLEL"
+(
+echo "<test type='performance' name='speedtest' >"
+echo "	<parameters parallel='$PARALLEL' start='`date`' />"
+echo "	<logfile>$DAILYDIR/$BUILDNUM/${LOGNAME}_$BUILDNUM.log</logfile>"
+MAKEFILE=$TESTBASE/test$CODEFACTOR.mk
+echo ""
+
+OUTDIR="$DAILYDIR/$BUILDNUM"
+TIMELOG="$OUTDIR/${LOGNAME}_$BUILDNUM.time"
+
+echo "	<build number='$BUILDNUM' of='$KEY' output='$OUTDIR'><![CDATA["
+if [ ! -d "$OUTDIR" ]; then
+	mkdir -p "$OUTDIR" || exit 1
+fi
+set -x
+
+# Make sure that our "stop signal" is clear
+SIGNALTOSTOPFILE="$OUTDIR/${LOGNAME}_$BUILDNUM.stop"
+rm -f "$SIGNALTOSTOPFILE"
+
+
+echo "EPOCROOT is $EPOCROOT"
+export PATH=$EPOCROOT/epoc32/tools:$PATH
+
+(
+echo "Annihilating epoc32 tree(s)"
+# wipe the epoc32 directory first
+chmod -R u+rw "$EPOCROOT/epoc32" &&
+rm -rf "$EPOCROOT/epoc32" &&
+echo "epoc32 tree withered" 
+) 
+(
+# unzip the pre-prepared epoc32 trees
+cd $EPOCROOT && 	
+(
+	unzip -o $BUILDROOT/epoc32.zip  | grep "epoc32/" | sed 's#.* \(epoc32/.*\)#\1#' | xargs touch && 
+	unzip -o $BUILDROOT/variant.zip  | grep "epoc32/" | sed 's#.* \(epoc32/.*\)#\1#' | xargs touch
+) > "$OUTDIR/unzip" &&
+chmod -R u+rw "$EPOCROOT/epoc32" &&
+echo "unzipped skeleton epoc32 tree" 
+) && (
+echo "Pre-export"
+$SBS_HOME/bin/sbs  -d -k -s "$PREEXPORTSYSDEF" -a "$SOURCEROOT" -c $PLATFORM EXPORT > $OUTDIR/${LOGNAME}_$BUILDNUM.preexport 2>&1 || {
+	echo "Pre-export failed";
+	exit 1
+}
+)
+
+echo "Prepping makefiles"
+(
+	echo "<times>\n"
+	export TIMEFORMAT=$'<time stage='prepmake'>%3R</time>\n'
+	time cp performance_Makefile $EPOCROOT/epoc32/build/Makefile
+)  > "$TIMELOG" 2>&1
+
+echo "Running Make"
+(
+	# The build process
+	 export TIMEFORMAT=$'<time stage='make' parallel='$PARALLEL'>%3R</time>\n'
+
+	time /usr/local/raptor/make-pvm-381/pvmgmake -j$PARALLEL --debug=j -k -f $MAKEFILE  > "$OUTDIR/${LOGNAME}_$BUILDNUM.log" 2>&1 
+	touch "$SIGNALTOSTOPFILE"
+	echo "</times>\n"
+) >> "$TIMELOG" 2>&1 & 
+(
+	set +x
+	# Concurrent process to continuously update statistics
+	echo ""
+
+	while [ 1 -eq 1 ]; do
+		sleep 20 
+		echo -n "."
+
+		if [ -e "$SIGNALTOSTOPFILE" ]; then
+			rm -f "$SIGNALTOSTOPFILE"
+			break
+		fi
+	done
+	echo ""
+)
+set +x
+genstats "$OUTDIR/${LOGNAME}_$BUILDNUM"
+
+echo "	]]></build>"
+echo "</test>"
+) >> "$TESTLOG" 2>&1
+
+BUILDNUM=$[ $BUILDNUM + 1 ]
+# use a new output directory
+done # PARALLEL
+echo -e "<testrun_stat endtime='`date`'\n />" >> "$TESTLOG"
+echo "</testrun>" >> "$TESTLOG"
--- a/sbsv2/raptor/bin/squashlog.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/squashlog.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,62 +1,62 @@
-#
-# 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: 
-# squash a raptor log file by removing commands from successful recipes
-#
-
-import sys
-
-inRecipe = False
-
-for line in sys.stdin.readlines():
-	# escape % characters otherwise print will fail
-	line = line.replace("%", "%%")
-		
-	# detect the start of a recipe
-	if line.startswith("<recipe "):
-		inRecipe = True
-		recipeLines = [line]
-		squashRecipe = True
-		continue
-		
-	# detect the status report from a recipe
-	if line.startswith("<status "):
-		if not "exit='ok'" in line:
-			# only squash ok recipes
-			squashRecipe = False
-		recipeLines.append(line)
-		continue
-				
-	# detect the end of a recipe
-	if line.startswith("</recipe>"):
-		# print the recipe
-		if squashRecipe:
-			for text in recipeLines:
-				if not text.startswith("+"):
-					print text,
-		else:
-			for text in recipeLines:
-				print text,
-		print line,
-		continue
-		
-	# remember the lines during a recipe
-	if inRecipe:
-		recipeLines.append(line)	
-	else:
-	# print all lines outside a recipe 
-		print line,
-	
-# end
-
+#
+# 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: 
+# squash a raptor log file by removing commands from successful recipes
+#
+
+import sys
+
+inRecipe = False
+
+for line in sys.stdin.readlines():
+	# escape % characters otherwise print will fail
+	line = line.replace("%", "%%")
+		
+	# detect the start of a recipe
+	if line.startswith("<recipe "):
+		inRecipe = True
+		recipeLines = [line]
+		squashRecipe = True
+		continue
+		
+	# detect the status report from a recipe
+	if line.startswith("<status "):
+		if not "exit='ok'" in line:
+			# only squash ok recipes
+			squashRecipe = False
+		recipeLines.append(line)
+		continue
+				
+	# detect the end of a recipe
+	if line.startswith("</recipe>"):
+		# print the recipe
+		if squashRecipe:
+			for text in recipeLines:
+				if not text.startswith("+"):
+					print text,
+		else:
+			for text in recipeLines:
+				print text,
+		print line,
+		continue
+		
+	# remember the lines during a recipe
+	if inRecipe:
+		recipeLines.append(line)	
+	else:
+	# print all lines outside a recipe 
+		print line,
+	
+# end
+
--- a/sbsv2/raptor/bin/statcollate.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/statcollate.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,112 +1,112 @@
-#
-# 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: 
-# statcollate
-#
-
-"""
-	Produce output for a graphing program or spreadsheet from
-	the statistic logs produced by buildstats.py from Raptor logs.
-	e.g. by analysing several logs we can see how
-	"number of successful compiles" improves over time.
-"""
-
-import sys
-from optparse import OptionParser
-import os
-import xml.dom.minidom
-from stat import *
-
-namespace = "http://symbian.com/2007/xml/build/raptor/stats"
-
-class StatsFail(Exception):
-	pass
-
-def pullStats(statnames, file):
-	"""Load a Statistics document and pull stats for a graph"""
-
-	# try to read and parse the XML file
-	try:
-	    dom = xml.dom.minidom.parse(file)
-
-	except Exception,e: # a whole bag of exceptions can be raised here
-		print "pullStats: %s" % str(e)
-		raise StatsFail
-
-	# <build> is always the root element
-	stats = dom.documentElement
-	objects = []
-	build = stats.childNodes[1]
-	
-	# create a Data Model object from each sub-element
-	output = {}
-	output['date'] = build.getAttribute('date')
-	#print "statnames %s\n" % str(statnames)   #test
-	for child in build.childNodes:
-	    if child.namespaceURI == namespace \
-        and child.nodeType == child.ELEMENT_NODE \
-        and child.hasAttributes():
-                #print "child node %s\n" % child.getAttribute('name')   #test
-                name = child.getAttribute('name')
-                if name in statnames:
-                    #print "1"  #test
-                    output[name] = child.getAttribute('count')
-
-	return output
-
-statnames = ['postlink success', 'compile success', 'compile fail']
-
-## Command Line Interface ################################################
-
-parser = OptionParser(prog = "statgraph",
-        usage = "%prog [-h | options] [<statsfile>] [[<statsfile>] ...]")
-
-(options, args) = parser.parse_args()
-
-statfilename = "stdin"
-
-table = sys.stdout
-print >> table, 'Date,',  # add 'Date' in front of names
-
-comma=""
-for name in statnames:
-    print >> table, comma+name, #! this order is not the order in dictionary
-    comma=', '
-    #print 'test,',  #test
-
-print >> table, ""
-
-if len(args) > 0:
-    for statfilename in args:
-        sys.__stderr__.write("Loading %s\n" % statfilename)
-        file = open(statfilename, "r")
-        try:
-            stats = pullStats(statnames, file)
-        except StatsFail,e:
-            sys.__stderr__.write("Can't process file %s\n" % statfilename)
-            sys.exit(1)
-        #print stats.items()  # test
-        file.close()
-        
-	comma=""
-        print >> table, stats['date'] + ",",
-        for name in statnames:
-            print >> table, comma+stats[name],
-    	    comma=', '
-            #print 'test,',  # test
-        print >> table, ""
-
-else:
-    sys.stderr.write("No files specified")
-    #pullStats(statnames,sys.stdin)
+#
+# 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: 
+# statcollate
+#
+
+"""
+	Produce output for a graphing program or spreadsheet from
+	the statistic logs produced by buildstats.py from Raptor logs.
+	e.g. by analysing several logs we can see how
+	"number of successful compiles" improves over time.
+"""
+
+import sys
+from optparse import OptionParser
+import os
+import xml.dom.minidom
+from stat import *
+
+namespace = "http://symbian.com/2007/xml/build/raptor/stats"
+
+class StatsFail(Exception):
+	pass
+
+def pullStats(statnames, file):
+	"""Load a Statistics document and pull stats for a graph"""
+
+	# try to read and parse the XML file
+	try:
+	    dom = xml.dom.minidom.parse(file)
+
+	except Exception,e: # a whole bag of exceptions can be raised here
+		print "pullStats: %s" % str(e)
+		raise StatsFail
+
+	# <build> is always the root element
+	stats = dom.documentElement
+	objects = []
+	build = stats.childNodes[1]
+	
+	# create a Data Model object from each sub-element
+	output = {}
+	output['date'] = build.getAttribute('date')
+	#print "statnames %s\n" % str(statnames)   #test
+	for child in build.childNodes:
+	    if child.namespaceURI == namespace \
+        and child.nodeType == child.ELEMENT_NODE \
+        and child.hasAttributes():
+                #print "child node %s\n" % child.getAttribute('name')   #test
+                name = child.getAttribute('name')
+                if name in statnames:
+                    #print "1"  #test
+                    output[name] = child.getAttribute('count')
+
+	return output
+
+statnames = ['postlink success', 'compile success', 'compile fail']
+
+## Command Line Interface ################################################
+
+parser = OptionParser(prog = "statgraph",
+        usage = "%prog [-h | options] [<statsfile>] [[<statsfile>] ...]")
+
+(options, args) = parser.parse_args()
+
+statfilename = "stdin"
+
+table = sys.stdout
+print >> table, 'Date,',  # add 'Date' in front of names
+
+comma=""
+for name in statnames:
+    print >> table, comma+name, #! this order is not the order in dictionary
+    comma=', '
+    #print 'test,',  #test
+
+print >> table, ""
+
+if len(args) > 0:
+    for statfilename in args:
+        sys.__stderr__.write("Loading %s\n" % statfilename)
+        file = open(statfilename, "r")
+        try:
+            stats = pullStats(statnames, file)
+        except StatsFail,e:
+            sys.__stderr__.write("Can't process file %s\n" % statfilename)
+            sys.exit(1)
+        #print stats.items()  # test
+        file.close()
+        
+	comma=""
+        print >> table, stats['date'] + ",",
+        for name in statnames:
+            print >> table, comma+stats[name],
+    	    comma=', '
+            #print 'test,',  # test
+        print >> table, ""
+
+else:
+    sys.stderr.write("No files specified")
+    #pullStats(statnames,sys.stdin)
--- a/sbsv2/raptor/bin/unsplitdirs.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/unsplitdirs.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,101 +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: 
-# unsplitdirs utility
-# This utility converts a directory tree which may contain "splits" due to case inconsistencies into
-# a combined form.  This is best illustrated as follows:
-# epoc32/RELEASE/ARMV5/urel
-# epoc32/Release/armv5/UREL
-# epoc32/RELEASE/armv5/Urel
-# are "healed by this script into:
-# epoc32/RELEASE/ARMV5/urel  (i.e. the first occurrence.
-#
-
-#
-# Files within these directories are maintained. i.e. it is possible to fix 
-# a directory tree with files already left in it.
-#
- 
-
-import os
-import os.path
-import re
-import sys
-import shutil
-from  optparse import OptionParser
-
-def mergetwo(firstdir, seconddir):
-# Move files from firstdir into seconddir.  If firstdir and seconddir both have 
-# a directory "X" then combines the contents of theses
-	for d in os.listdir(firstdir):
-		fileitem = os.path.join(firstdir,d)
-		dest = os.path.join(seconddir,d)
-		print "moving %s, %s to %s " % (d, fileitem, dest)
-		if os.path.isdir(dest) and os.path.isdir(fileitem):
-			mergetwo(fileitem, dest)
-			try:
-				os.rmdir(fileitem)
-			except:
-				print "\tfailed rmdir %s" % fileitem
-		else:
-			shutil.move(fileitem, dest)
-	try:
-		os.rmdir(firstdir)
-	except:
-		print "\tfailed rmdir %s" % firstdir
-	
-	
-
-def visit(dirname, link = False):
-# Find directories with names that differ only in case
-	nameclash = {}
-#	print "dir %s\n" %(dirname)
-	for f in os.listdir(dirname):
-		fullpath = os.path.join(dirname,f)
-		if os.path.isdir(fullpath) and not os.path.islink(fullpath):
-		#	print "\tmergeable %s" %(f)
-			fl = f.lower()
-			if nameclash.has_key(fl):
-				mergetwo(fullpath, os.path.join(dirname, nameclash[fl]))
-				if link:
-					print "\tlinking %s <- %s" %(nameclash[fl], fullpath)
-					os.symlink(nameclash[fl], fullpath)
-			else:
-				nameclash[fl] = f
-		else:
-			pass
-		#	print "%s is not a dir\n" %(f)
-
-	for d in nameclash.values():
-	#	print "\tVisiting %s" %(d)
-		visit(os.path.join(dirname, d))
-
-
-dirname = sys.argv[1]
-
-parser = OptionParser(prog = "unsplitdirs",
-        usage = "%prog [-h | options] [<file>]")
-
-parser.add_option("-l", "--link", default = False,
-         action="store_true", dest="link", help="Turn mismatched-case directories into symbolic links e.g. if armv5 is the default then make the link ARMV5->armv5")
-
-(options, args) = parser.parse_args()
-
-logname="stdin"
-if len(args) > 0:
-        dirname = args[0]
-else:
-	dirname ='.'
-
-visit(dirname, options.link)
+#
+# 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: 
+# unsplitdirs utility
+# This utility converts a directory tree which may contain "splits" due to case inconsistencies into
+# a combined form.  This is best illustrated as follows:
+# epoc32/RELEASE/ARMV5/urel
+# epoc32/Release/armv5/UREL
+# epoc32/RELEASE/armv5/Urel
+# are "healed by this script into:
+# epoc32/RELEASE/ARMV5/urel  (i.e. the first occurrence.
+#
+
+#
+# Files within these directories are maintained. i.e. it is possible to fix 
+# a directory tree with files already left in it.
+#
+ 
+
+import os
+import os.path
+import re
+import sys
+import shutil
+from  optparse import OptionParser
+
+def mergetwo(firstdir, seconddir):
+# Move files from firstdir into seconddir.  If firstdir and seconddir both have 
+# a directory "X" then combines the contents of theses
+	for d in os.listdir(firstdir):
+		fileitem = os.path.join(firstdir,d)
+		dest = os.path.join(seconddir,d)
+		print "moving %s, %s to %s " % (d, fileitem, dest)
+		if os.path.isdir(dest) and os.path.isdir(fileitem):
+			mergetwo(fileitem, dest)
+			try:
+				os.rmdir(fileitem)
+			except:
+				print "\tfailed rmdir %s" % fileitem
+		else:
+			shutil.move(fileitem, dest)
+	try:
+		os.rmdir(firstdir)
+	except:
+		print "\tfailed rmdir %s" % firstdir
+	
+	
+
+def visit(dirname, link = False):
+# Find directories with names that differ only in case
+	nameclash = {}
+#	print "dir %s\n" %(dirname)
+	for f in os.listdir(dirname):
+		fullpath = os.path.join(dirname,f)
+		if os.path.isdir(fullpath) and not os.path.islink(fullpath):
+		#	print "\tmergeable %s" %(f)
+			fl = f.lower()
+			if nameclash.has_key(fl):
+				mergetwo(fullpath, os.path.join(dirname, nameclash[fl]))
+				if link:
+					print "\tlinking %s <- %s" %(nameclash[fl], fullpath)
+					os.symlink(nameclash[fl], fullpath)
+			else:
+				nameclash[fl] = f
+		else:
+			pass
+		#	print "%s is not a dir\n" %(f)
+
+	for d in nameclash.values():
+	#	print "\tVisiting %s" %(d)
+		visit(os.path.join(dirname, d))
+
+
+dirname = sys.argv[1]
+
+parser = OptionParser(prog = "unsplitdirs",
+        usage = "%prog [-h | options] [<file>]")
+
+parser.add_option("-l", "--link", default = False,
+         action="store_true", dest="link", help="Turn mismatched-case directories into symbolic links e.g. if armv5 is the default then make the link ARMV5->armv5")
+
+(options, args) = parser.parse_args()
+
+logname="stdin"
+if len(args) > 0:
+        dirname = args[0]
+else:
+	dirname ='.'
+
+visit(dirname, options.link)
--- a/sbsv2/raptor/bin/vartoxml.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/vartoxml.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,207 +1,207 @@
-#
-# 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: 
-# Raptor Binary Variation var file to xml spec generator
-# Given a set of .var files, this script will generate an xml specification file
-#
-
-
-import sys,os,re,fnmatch
-import xml.dom.minidom 
-from optparse import OptionParser
-
-doc = xml.dom.minidom.Document()
-class VarFile:
-
-	def __init__(self,aFile):
-		self.virtual = False
-		self.varname = ""
-		self.varhrh = ""
-		self.build_include = ""
-		self.rom_include = ""
-		self.extends = ""
-		self.file = aFile
-
-	# Parse the var file
-	def ParseVarFile(self):
-		file = open(self.file)
-		vardata = file.readlines()
-		for var in vardata:
-			if re.match('VARIANT\s+(?P<VARIANTNAME>\w+)',var):
-				self.varname = re.match('VARIANT\s+(?P<VARIANTNAME>\w+)',var)
-			elif re.match('VARIANT_HRH\s+(?P<VARIANTHRH>.+)',var):
-				self.varhrh  = re.match('VARIANT_HRH\s+(?P<VARIANTHRH>.+)',var)
-			elif re.match('VIRTUAL\s+$',var):
-				self.virtual = True
-			elif re.match('BUILD_INCLUDE\s+.+',var):
-				self.build_include = re.match('BUILD_INCLUDE\s+(?P<PROPERTY>\w+)\s+(?P<LOCATION>.+)',var)
-			elif re.match('ROM_INCLUDE\s+.+',var):
-				self.rom_include = re.match('ROM_INCLUDE\s+(?P<PROPERTY>\w+)\s+(?P<LOCATION>.+)',var)
-			elif re.match('EXTENDS\s+(?P<EXTENDS>\w+)',var):
-				self.extends = re.match('EXTENDS\s+(?P<EXTENDSNODE>\w+)',var)
-		if self.varname:
-			self.varname = self.varname.group('VARIANTNAME')
-		if self.varhrh:
-			self.varhrh  = self.varhrh.group('VARIANTHRH')
-		if self.extends:
-			self.extends = self.extends.group('EXTENDSNODE')
-		file.close()
-	
-	# Write the specs for a variant object and attach it to a parent node
-	def CreateSpec(self,parentNode):
-	
-		var = doc.createElement("var")
-		parentNode.appendChild(var)
-
-		# Set the FEATUREVARIANT name
-		vname = doc.createElement("set")
-		vname.setAttribute("name","FEATUREVARIANT")
-		vname.setAttribute("value",self.varname)
-		if self.virtual:
-			vname.setAttribute("abstract","true")
-		var.appendChild(vname)
-
-		# Set the VARIANT_HRH name
-		hrhname = doc.createElement("set")
-		hrhname.setAttribute("name","VARIANT_HRH")
-		hrhname.setAttribute("value",self.varhrh)
-		var.appendChild(hrhname)
-
-		# Set the build includes
-		if self.build_include:
-			buildincs = doc.createElement(self.build_include.group('PROPERTY'))
-			buildincs.setAttribute("name","BUILD_INCLUDE")
-			buildincs.setAttribute("value",self.build_include.group('LOCATION'))
-			var.appendChild(buildincs)
-
-		# Set the rom includes
-		if self.rom_include:
-			buildincs = doc.createElement(self.rom_include.group('PROPERTY'))
-			buildincs.setAttribute("name","ROM_INCLUDE")
-			buildincs.setAttribute("value",self.rom_include.group('LOCATION'))
-			var.appendChild(buildincs)
-
-# Main function
-def main():
-
-	parser = OptionParser(prog = "vartoxml.py")
-	parser.add_option("-s","--sourcefile",action="append",dest="varfile",help="List of var files")
-	parser.add_option("-o","--output",action="store",dest="outputxml",help="Output xml file")
-	parser.add_option("-d","--folder",action="store",dest="folder",help="Folder names to search for var files")
-
-	(options, leftover_args) = parser.parse_args(sys.argv[1:])
-	
-	childlist = [] 
-	addedlist = []
-	nodesList = []
-	childnames = []
-	i = 0
-	
-	# Get the list of .var file from the specified folder(s)
-	if options.folder:
-		for folder in options.folder:
-			for fileName in os.listdir (folder):
-				if fnmatch.fnmatch (fileName,'*.var'):
-					if options.varfile:
-						options.varfile.append(fileName)
-					else:
-						options.varfile = []
-						options.varfile.append(fileName)
-	
-	# We need some source files for this script to work
-	if not options.varfile:
-		print "Error: No source files specified "
-		sys.exit()
-		
-	# Set parent node to gibberish
-	parentNode = doc.createElement("build")
-	doc.appendChild(parentNode)
-	newparentNode = ""
-	
-	# Removes duplicate elements in the arguments and iterate through them
-	# to find the top-level abstract parent node
-	for arg in list(set(options.varfile)):
-		varobj = VarFile(arg)
-		varobj.ParseVarFile()
-		if varobj.extends:
-			childlist.append(varobj)
-		else:
-			addedlist.append(varobj)
-			conf = doc.createElement("config")
-			conf.setAttribute("name",varobj.varname)
-			parentNode.appendChild(conf)
-			varobj.CreateSpec(conf)
-			nodesList.append(conf)
-	
-	# Names of all the children need to be stored separately
-	for c in childlist:
-		childnames.append(c.varname)
-
-	childlist2 = list(childlist)
-
-	# Check the list is correct, and append orphan nodes to master BUILD node
-	for ch in childlist2:
-		if addedlist:
-			if not ch.extends in addedlist[0].varname:
-				if not ch.extends in childnames:
-					conf = doc.createElement("config")
-					conf.setAttribute("name",ch.varname)
-					parentNode.appendChild(conf)
-					varobj.CreateSpec(conf)
-					nodesList.append(conf)
-					addedlist.append(ch)
-					childlist.remove(ch)
-		else:
-			if not ch.extends in childnames:
-				conf = doc.createElement("config")
-				conf.setAttribute("name",ch.varname)
-				parentNode.appendChild(conf)
-				varobj.CreateSpec(conf)
-				nodesList.append(conf)
-				addedlist.append(ch)
-				childlist.remove(ch)
-				
-	# Make a copy of the new childlist
-	childlist2 = list(childlist)
-
-	# Go through all the children, and add them to the xml spec
-	while (childlist2):
-		# Refactor the childlist to remove elements which have been added
-		for add in addedlist:
-			if add in childlist:
-				childlist.remove(add)
-		for ch in childlist:
-			if ch.extends == addedlist[i].varname:
-				addedlist.append(ch)
-				childlist2.remove(ch)
-				conf = doc.createElement("config")
-				conf.setAttribute("name",ch.varname)
-				nodesList[i].appendChild(conf)
-				nodesList.append(conf)
-				ch.CreateSpec(conf)
-			else:
-				pass
-		i = i + 1
-	
-	# If output xml file is specified, write to it otherwise print the xml to screen
-	if options.outputxml:
-		file = open(options.outputxml,"w")
-		file.writelines(doc.toprettyxml(indent="  "))
-		file.close()
-	else:
-		print doc.toprettyxml(indent="  ")
-
-
-if __name__ == "__main__":
-    main()
+#
+# 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: 
+# Raptor Binary Variation var file to xml spec generator
+# Given a set of .var files, this script will generate an xml specification file
+#
+
+
+import sys,os,re,fnmatch
+import xml.dom.minidom 
+from optparse import OptionParser
+
+doc = xml.dom.minidom.Document()
+class VarFile:
+
+	def __init__(self,aFile):
+		self.virtual = False
+		self.varname = ""
+		self.varhrh = ""
+		self.build_include = ""
+		self.rom_include = ""
+		self.extends = ""
+		self.file = aFile
+
+	# Parse the var file
+	def ParseVarFile(self):
+		file = open(self.file)
+		vardata = file.readlines()
+		for var in vardata:
+			if re.match('VARIANT\s+(?P<VARIANTNAME>\w+)',var):
+				self.varname = re.match('VARIANT\s+(?P<VARIANTNAME>\w+)',var)
+			elif re.match('VARIANT_HRH\s+(?P<VARIANTHRH>.+)',var):
+				self.varhrh  = re.match('VARIANT_HRH\s+(?P<VARIANTHRH>.+)',var)
+			elif re.match('VIRTUAL\s+$',var):
+				self.virtual = True
+			elif re.match('BUILD_INCLUDE\s+.+',var):
+				self.build_include = re.match('BUILD_INCLUDE\s+(?P<PROPERTY>\w+)\s+(?P<LOCATION>.+)',var)
+			elif re.match('ROM_INCLUDE\s+.+',var):
+				self.rom_include = re.match('ROM_INCLUDE\s+(?P<PROPERTY>\w+)\s+(?P<LOCATION>.+)',var)
+			elif re.match('EXTENDS\s+(?P<EXTENDS>\w+)',var):
+				self.extends = re.match('EXTENDS\s+(?P<EXTENDSNODE>\w+)',var)
+		if self.varname:
+			self.varname = self.varname.group('VARIANTNAME')
+		if self.varhrh:
+			self.varhrh  = self.varhrh.group('VARIANTHRH')
+		if self.extends:
+			self.extends = self.extends.group('EXTENDSNODE')
+		file.close()
+	
+	# Write the specs for a variant object and attach it to a parent node
+	def CreateSpec(self,parentNode):
+	
+		var = doc.createElement("var")
+		parentNode.appendChild(var)
+
+		# Set the FEATUREVARIANT name
+		vname = doc.createElement("set")
+		vname.setAttribute("name","FEATUREVARIANT")
+		vname.setAttribute("value",self.varname)
+		if self.virtual:
+			vname.setAttribute("abstract","true")
+		var.appendChild(vname)
+
+		# Set the VARIANT_HRH name
+		hrhname = doc.createElement("set")
+		hrhname.setAttribute("name","VARIANT_HRH")
+		hrhname.setAttribute("value",self.varhrh)
+		var.appendChild(hrhname)
+
+		# Set the build includes
+		if self.build_include:
+			buildincs = doc.createElement(self.build_include.group('PROPERTY'))
+			buildincs.setAttribute("name","BUILD_INCLUDE")
+			buildincs.setAttribute("value",self.build_include.group('LOCATION'))
+			var.appendChild(buildincs)
+
+		# Set the rom includes
+		if self.rom_include:
+			buildincs = doc.createElement(self.rom_include.group('PROPERTY'))
+			buildincs.setAttribute("name","ROM_INCLUDE")
+			buildincs.setAttribute("value",self.rom_include.group('LOCATION'))
+			var.appendChild(buildincs)
+
+# Main function
+def main():
+
+	parser = OptionParser(prog = "vartoxml.py")
+	parser.add_option("-s","--sourcefile",action="append",dest="varfile",help="List of var files")
+	parser.add_option("-o","--output",action="store",dest="outputxml",help="Output xml file")
+	parser.add_option("-d","--folder",action="store",dest="folder",help="Folder names to search for var files")
+
+	(options, leftover_args) = parser.parse_args(sys.argv[1:])
+	
+	childlist = [] 
+	addedlist = []
+	nodesList = []
+	childnames = []
+	i = 0
+	
+	# Get the list of .var file from the specified folder(s)
+	if options.folder:
+		for folder in options.folder:
+			for fileName in os.listdir (folder):
+				if fnmatch.fnmatch (fileName,'*.var'):
+					if options.varfile:
+						options.varfile.append(fileName)
+					else:
+						options.varfile = []
+						options.varfile.append(fileName)
+	
+	# We need some source files for this script to work
+	if not options.varfile:
+		print "Error: No source files specified "
+		sys.exit()
+		
+	# Set parent node to gibberish
+	parentNode = doc.createElement("build")
+	doc.appendChild(parentNode)
+	newparentNode = ""
+	
+	# Removes duplicate elements in the arguments and iterate through them
+	# to find the top-level abstract parent node
+	for arg in list(set(options.varfile)):
+		varobj = VarFile(arg)
+		varobj.ParseVarFile()
+		if varobj.extends:
+			childlist.append(varobj)
+		else:
+			addedlist.append(varobj)
+			conf = doc.createElement("config")
+			conf.setAttribute("name",varobj.varname)
+			parentNode.appendChild(conf)
+			varobj.CreateSpec(conf)
+			nodesList.append(conf)
+	
+	# Names of all the children need to be stored separately
+	for c in childlist:
+		childnames.append(c.varname)
+
+	childlist2 = list(childlist)
+
+	# Check the list is correct, and append orphan nodes to master BUILD node
+	for ch in childlist2:
+		if addedlist:
+			if not ch.extends in addedlist[0].varname:
+				if not ch.extends in childnames:
+					conf = doc.createElement("config")
+					conf.setAttribute("name",ch.varname)
+					parentNode.appendChild(conf)
+					varobj.CreateSpec(conf)
+					nodesList.append(conf)
+					addedlist.append(ch)
+					childlist.remove(ch)
+		else:
+			if not ch.extends in childnames:
+				conf = doc.createElement("config")
+				conf.setAttribute("name",ch.varname)
+				parentNode.appendChild(conf)
+				varobj.CreateSpec(conf)
+				nodesList.append(conf)
+				addedlist.append(ch)
+				childlist.remove(ch)
+				
+	# Make a copy of the new childlist
+	childlist2 = list(childlist)
+
+	# Go through all the children, and add them to the xml spec
+	while (childlist2):
+		# Refactor the childlist to remove elements which have been added
+		for add in addedlist:
+			if add in childlist:
+				childlist.remove(add)
+		for ch in childlist:
+			if ch.extends == addedlist[i].varname:
+				addedlist.append(ch)
+				childlist2.remove(ch)
+				conf = doc.createElement("config")
+				conf.setAttribute("name",ch.varname)
+				nodesList[i].appendChild(conf)
+				nodesList.append(conf)
+				ch.CreateSpec(conf)
+			else:
+				pass
+		i = i + 1
+	
+	# If output xml file is specified, write to it otherwise print the xml to screen
+	if options.outputxml:
+		file = open(options.outputxml,"w")
+		file.writelines(doc.toprettyxml(indent="  "))
+		file.close()
+	else:
+		print doc.toprettyxml(indent="  ")
+
+
+if __name__ == "__main__":
+    main()
--- a/sbsv2/raptor/bin/whatsource.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/bin/whatsource.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,57 +1,57 @@
-#
-# 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: 
-#
-
-#!/bin/env python
-# What source files did the build try to build?
-
-import sys
-import re
-from  optparse import OptionParser
-from raptorlog import *
-
-
-def genstats(file, logitems):
-	linecount=0
-	print "<source>"
-	for l in file.xreadlines():
-		for i in logitems:
-			i.match(l)
-	print "</source>"
-
-
-## Command Line Interface ####################################################
-
-parser = OptionParser(prog = "whatsource",
-	usage = "%prog [-h | options] logfile\nFind out what source files the compiler tried to build")
-
-(options, args) = parser.parse_args()
-
-logname="stdin"
-if len(args) > 0:
-	logname=args[0]
-	file = open(logname,"r")
-else:
-	file = sys.stdin
-
-
-compiler_invocations = [ 
-	LogItem("armcc usage",'\+ .*armcc.*-c', True, '[A-Za-z0-9_/\-\.]+\.cpp'),
-	] 
-
-genstats(file, compiler_invocations)
-
-if file != sys.stdin:
-	file.close()
+#
+# 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: 
+#
+
+#!/bin/env python
+# What source files did the build try to build?
+
+import sys
+import re
+from  optparse import OptionParser
+from raptorlog import *
+
+
+def genstats(file, logitems):
+	linecount=0
+	print "<source>"
+	for l in file.xreadlines():
+		for i in logitems:
+			i.match(l)
+	print "</source>"
+
+
+## Command Line Interface ####################################################
+
+parser = OptionParser(prog = "whatsource",
+	usage = "%prog [-h | options] logfile\nFind out what source files the compiler tried to build")
+
+(options, args) = parser.parse_args()
+
+logname="stdin"
+if len(args) > 0:
+	logname=args[0]
+	file = open(logname,"r")
+else:
+	file = sys.stdin
+
+
+compiler_invocations = [ 
+	LogItem("armcc usage",'\+ .*armcc.*-c', True, '[A-Za-z0-9_/\-\.]+\.cpp'),
+	] 
+
+genstats(file, compiler_invocations)
+
+if file != sys.stdin:
+	file.close()
--- a/sbsv2/raptor/examples/os_properties.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/examples/os_properties.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,23 +1,24 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	
-	<!--
-	
-	Because Raptor is not part of the OS it needs to know some properties of
-	the OS that it is building. If you are building an older OS than the one
-	configured by default then you need to put a file like this one into the
-	folder EPOCROOT/epoc32/sbs_config
-	
-	The file can have any name as long as it ends with ".xml"
-	
-	-->
-	
-	<!-- changes required for v9.4, TB91, and TB91sf -->
-		 
-	<var name="root.changes">
-		<set name='POSTLINKER_SUPPORTS_WDP' value=''/>
-		<set name='SUPPORTS_STDCPP_NEWLIB' value=''/>
-		<set name='RVCT_PRE_INCLUDE' value='$(EPOCINCLUDE)/rvct2_2/rvct2_2.h'/>
-	</var>
-	
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	
+	<!--
+	
+	Because Raptor is not part of the OS it needs to know some properties of
+	the OS that it is building. If you are building an older OS than the one
+	configured by default then you need to put a file like this one into the
+	folder EPOCROOT/epoc32/sbs_config
+	
+	The file can have any name as long as it ends with ".xml"
+	
+	-->
+	
+	<!-- changes required for v9.4, TB91, and TB91sf -->
+		 
+	<var name="root.changes">
+		<set name='POSTLINKER_SUPPORTS_WDP' value=''/>
+		<set name='SUPPORTS_STDCPP_NEWLIB' value=''/>
+		<set name='RVCT_PRE_INCLUDE' value='$(EPOCINCLUDE)/rvct2_2/rvct2_2.h'/>
+		<set name="SUPPORTS_ABIV1_IMPLIBS" value='1'/>
+	</var>
+	
+</build>
--- a/sbsv2/raptor/examples/sbs_init.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/examples/sbs_init.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,127 +1,127 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-
-<build xmlns="http://symbian.com/xml/build"
-       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://symbian.com/xml/build build/2_0.xsd">
-
-	<!--
-
-	To change the defaults for Raptor, edit and copy this file
-	to $SBS_HOME
-
-	This will be used unless there is a file called $HOME/.sbs_init.xml
-	(note the "." before the "s") which will be used instead.
-
-	Read on to the next <var> to see other things you can do with this file.
-	
-	 -->
-
-	<var name="defaults.init">
-		<!-- environment variables used in this configuration -->
-		<env name="EPOCROOT" default="/" type="path"/>
-
-		<!-- default parameter settings -->
-
-		<!-- Make command parameter file -->
-		<set name="makeEngine" value="make"/>
-
-		<!-- Location of the highest level makefile -->
-		<set name="topMakefile" value="$(EPOCROOT)/epoc32/build/Makefile"/>
-
-		<!-- Name of the build logging file -->
-		<set name="logFileName" value="$(EPOCROOT)/epoc32/build/Makefile.%TIME.log"/>
-
-		<!-- Default build configuration name -->
-		<set name="defaultConfig" value="default"/>
-
-		<!-- Names of standard build files -->
-		<set name="buildInformation" value="bld.inf"/>
-		<set name="systemDefinition" value="System_Definition.xml"/>
-
-		<!-- Standard directories -->
-		<set name="systemConfig" value="lib/config"/>
-		<set name="systemFLM" value="lib/flm"/>
-		<set name="systemPlugins" value="python/plugins"/>
-		<set name="systemDefinitionBase" value="."/>
-
-		<!-- Do not print any information messages? -->
-		<set name="quiet" value="false"/>
-
-		<!-- How many jobs to run in parallel? (for make -j) -->
-		<set name="jobs" value="4"/>
-
-		<!-- How many attempts to run a job before recording an error?
-		This is useful for builds that can have transient failures. -->
-		<set name="tries" value="1"/>
-
-		<!-- Carry on trying to build even if some commands fail? -->
-		<set name="keepGoing" value="false"/>
-
-		<!-- Do we use a bld.inf or System_Definition.xml if both are in the CWD -->
-		<set name="preferBuildInfoToSystemDefinition" value="false"/>
-
-		<!-- Always use ignore OS detection? -->
-		<set name="ignoreOsDetection" value="false"/>
-
-		<!-- Always use a specific list of filters -->
-		<set name="filterList" value="FilterTerminal,FilterLogfile"/>
-
-	</var>
-
-	<!-- 
-	
-	Other variants can be defined and used on the command line. The "bob"
-	variant below adds a macro called "BOB" to a configuration. Use it by
-	typing the command:
-	
-	sbs -c armv5.bob -c winscw.bob
-	
-	-->
-	
-	<var name="bob">
-		<append name="CDEFS" value="BOB"/>
-	</var>
-	
-	<!--
-	
-	Aliases are used to give shorter names to strings of variants. Internally
-	things like armv5_urel are defined as aliases, so the following are the
-	same build:
-	
-	sbs -c armv5_urel
-	sbs -c arm.v5.urel.rvct2_2
-	
-	This means that you can re-define an alias to use a different compiler, for
-	example. The following aliases change the compiler used for armv5 and armv7
-	builds to be RVCT 4.0
-	
-	-->
-	
-	<alias name="armv5_urel" meaning="arm.v5.urel.rvct4_0"/>
-	<alias name="armv5_udeb" meaning="arm.v5.udeb.rvct4_0"/>
-
-	<alias name="armv7_urel" meaning="arm.v7.urel.rvct4_0"/>
-	<alias name="armv7_udeb" meaning="arm.v7.udeb.rvct4_0"/>
-	
-	<!--
-	
-	Groups allow a single -c option to expand into a set of build configurations
-	that are all done at the same time. Internally armv5 is a group of
-	armv5_urel and armv5_udeb. You can define your own groups and groups of
-	groups. The example below is a group which builds production and test code
-	for armv5 at the same time. Use it by typing the command:
-	
-	sbs -c armv5_all
-	
-	instead of:
-	
-	sbs -c armv5_urel -c armv5_udeb -c armv5_urel.test -c armv5_udeb.test
-	
-	-->
-	
-	<group name="armv5_all">
-		<groupRef ref="armv5"/>
-		<groupRef ref="armv5" mod="test"/>
-	</group>
-	
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+
+<build xmlns="http://symbian.com/xml/build"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xsi:schemaLocation="http://symbian.com/xml/build build/2_0.xsd">
+
+	<!--
+
+	To change the defaults for Raptor, edit and copy this file
+	to $SBS_HOME
+
+	This will be used unless there is a file called $HOME/.sbs_init.xml
+	(note the "." before the "s") which will be used instead.
+
+	Read on to the next <var> to see other things you can do with this file.
+	
+	 -->
+
+	<var name="defaults.init">
+		<!-- environment variables used in this configuration -->
+		<env name="EPOCROOT" default="/" type="path"/>
+
+		<!-- default parameter settings -->
+
+		<!-- Make command parameter file -->
+		<set name="makeEngine" value="make"/>
+
+		<!-- Location of the highest level makefile -->
+		<set name="topMakefile" value="$(EPOCROOT)/epoc32/build/Makefile"/>
+
+		<!-- Name of the build logging file -->
+		<set name="logFileName" value="$(EPOCROOT)/epoc32/build/Makefile.%TIME.log"/>
+
+		<!-- Default build configuration name -->
+		<set name="defaultConfig" value="default"/>
+
+		<!-- Names of standard build files -->
+		<set name="buildInformation" value="bld.inf"/>
+		<set name="systemDefinition" value="System_Definition.xml"/>
+
+		<!-- Standard directories -->
+		<set name="systemConfig" value="lib/config"/>
+		<set name="systemFLM" value="lib/flm"/>
+		<set name="systemPlugins" value="python/plugins"/>
+		<set name="systemDefinitionBase" value="."/>
+
+		<!-- Do not print any information messages? -->
+		<set name="quiet" value="false"/>
+
+		<!-- How many jobs to run in parallel? (for make -j) -->
+		<set name="jobs" value="4"/>
+
+		<!-- How many attempts to run a job before recording an error?
+		This is useful for builds that can have transient failures. -->
+		<set name="tries" value="1"/>
+
+		<!-- Carry on trying to build even if some commands fail? -->
+		<set name="keepGoing" value="false"/>
+
+		<!-- Do we use a bld.inf or System_Definition.xml if both are in the CWD -->
+		<set name="preferBuildInfoToSystemDefinition" value="false"/>
+
+		<!-- Always use ignore OS detection? -->
+		<set name="ignoreOsDetection" value="false"/>
+
+		<!-- Always use a specific list of filters -->
+		<set name="filterList" value="FilterTerminal,FilterLogfile"/>
+
+	</var>
+
+	<!-- 
+	
+	Other variants can be defined and used on the command line. The "bob"
+	variant below adds a macro called "BOB" to a configuration. Use it by
+	typing the command:
+	
+	sbs -c armv5.bob -c winscw.bob
+	
+	-->
+	
+	<var name="bob">
+		<append name="CDEFS" value="BOB"/>
+	</var>
+	
+	<!--
+	
+	Aliases are used to give shorter names to strings of variants. Internally
+	things like armv5_urel are defined as aliases, so the following are the
+	same build:
+	
+	sbs -c armv5_urel
+	sbs -c arm.v5.urel.rvct2_2
+	
+	This means that you can re-define an alias to use a different compiler, for
+	example. The following aliases change the compiler used for armv5 and armv7
+	builds to be RVCT 4.0
+	
+	-->
+	
+	<alias name="armv5_urel" meaning="arm.v5.urel.rvct4_0"/>
+	<alias name="armv5_udeb" meaning="arm.v5.udeb.rvct4_0"/>
+
+	<alias name="armv7_urel" meaning="arm.v7.urel.rvct4_0"/>
+	<alias name="armv7_udeb" meaning="arm.v7.udeb.rvct4_0"/>
+	
+	<!--
+	
+	Groups allow a single -c option to expand into a set of build configurations
+	that are all done at the same time. Internally armv5 is a group of
+	armv5_urel and armv5_udeb. You can define your own groups and groups of
+	groups. The example below is a group which builds production and test code
+	for armv5 at the same time. Use it by typing the command:
+	
+	sbs -c armv5_all
+	
+	instead of:
+	
+	sbs -c armv5_urel -c armv5_udeb -c armv5_urel.test -c armv5_udeb.test
+	
+	-->
+	
+	<group name="armv5_all">
+		<groupRef ref="armv5"/>
+		<groupRef ref="armv5" mod="test"/>
+	</group>
+	
+</build>
--- a/sbsv2/raptor/lib/config/arm.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/arm.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,156 +1,167 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- build configurations for ARM compilers -->
-	<var name="arm" extends="root">
-		<varRef ref="default.interfaces"/>
-		<varRef ref="default.locations"/>
-		<env name="EFREEZE" default="$(PERL) $(EPOCROOT)/epoc32/tools/efreeze.pl" type="tool"/>
-		<!-- picked up from the Environment -->
-		<env name="ELF2E32" default="$(EPOCROOT)/epoc32/tools/elf2e32$(DOTEXE)" type="tool"/>
-		<env name="BMCONV" default="$(EPOCROOT)/epoc32/tools/bmconv$(DOTEXE)" type="tool"/>
-		<env name="CHECKLIB" default="$(EPOCROOT)/epoc32/tools/checklib$(DOTEXE)" type="tool"/>
-		<env name="TRANASM" default="$(PERL) $(EPOCROOT)/epoc32/tools/tranasm.pl" type="tool"/>
-		<env name="CPPFILT" default="$(GCCPREFIX)c++filt$(DOTEXE)" type="tool"/>
-		<env name="RCOMP" default="$(EPOCROOT)/epoc32/tools/rcomp$(DOTEXE)" type="tool"/>
-		<env name="PREPDEF" default="$(PERL) $(EPOCROOT)/epoc32/tools/prepdef.pl" type="path"/>
-		<env name="STRINGTABLE" default="$(PERL) $(EPOCROOT)/epoc32/tools/stringtable.pl" type="path"/>
-		<!-- RANSLEEP is a program that can be used to cause a random delay in milliseconds. This is only useful in parallel builds.  See the PERTURBSTARTTIME switch for more details.  -->
-		<env name="RANSLEEP" default="$(SBS_HOME)/bin/$(HOSTPLATFORM_DIR)/ransleep$(DOTEXE)" type="tool"/>
-		<set name="BLDINF_OUTPUTPATH" value="$(SBS_BUILD_DIR)"/>
-		<set name="CDEFS" value=""/>	
-		<!-- arm specific interfaces -->
-		<set name="INTERFACE.extension" value="Symbian.extension"/>
-		<!-- link to bld.inf and mmp platform names -->
-		<set name="ARMMACROS" value="__MARM_ARMV5__ $(ARMMACROS.CONFIG) $(ARMMACROS.VAR)"/>
-		<set name="ARMMACROS.CONFIG" value=""/>
-		<set name="ARMMACROS.VAR" value=""/>
-		<set name="CAPABILITY" value=""/>
-		<set name="CODE_SEGMENT_START" value=""/>
-		<set name="DEFAULT_STDCPP_NEWLIB" value="stdnew.dso"/>
-		<set name="DEFAULT_SYMBIAN_NEWLIB" value="scppnwdl.dso"/>
-		<set name="FULLVARIANTPATH" value="$(VARIANTPLATFORM)/$(VARIANTTYPE)"/>
-		<set name="HEADER_FILES_CONTROL_OPTION" value=""/>
-		<set name="LIBRARY_DEBUG" value=""/>
-		<set name="MMPDEFS" value=""/>
-		<set name="NMAKE" value="nmake"/>
-		<set name="NMAKEFLAGS" value="-nologo -x - "/>
-		<set name="OUTPUTPATH" value="$(SBS_BUILD_DIR)"/>
-		<set name="PERTURBSTARTTIME" value=""/>
-		<!-- add a random delay before starting armcc or armlink to ease contention for licensesthe maximum time to delay in milliseconds. RANSLEEP program must be available.   -->
-		<set name="PERTURBMSECS" value="500"/>
-		<!-- the maximum time to delay in milliseconds -->
-		<set name="BLDINF_OUTPUTPATH" value="$(SBS_BUILD_DIR)"/>
-		<set name="RELEASEPATH" value="$(EPOCROOT)/epoc32/release"/>
-		<set name="RESOLVED_DEFFILE" value=""/>
-		<set name="RUNTIME_LIBS_PATH" value="$(EPOCROOT)/epoc32/release/armv5/lib"/>
-		<set name="SBSV1MAKE" value="$(EPOCROOT)/epoc32/tools/make$(DOTEXE)"/>
-		<set name="SID" value=""/>
-		<set name="EPOCSTACKSIZE" value=""/>
-		<set name="STATIC_LIBRARY_DIR" value="$(EPOCROOT)/epoc32/release/$(VARIANTPLATFORM)/$(VARIANTTYPE)"/>
-		<set name="STATIC_RUNTIME_DIR" value="$(EPOCROOT)/epoc32/release/$(VARIANTPLATFORM)/$(VARIANTTYPE)"/>
-		<set name="SYMBIAN_CC_MESSAGE_OPTION" value="$(CC_WARNINGS_CONTROL_OPTION) $(CC_ERRORS_CONTROL_OPTION)"/>
-		<set name="SYMBIAN_DLL_DEFINITION" value="__DLL__"/>
-		<set name="SYMBIAN_EXE_DEFINITION" value="__EXE__"/>
-		<set name="SYMBIAN_LINK_FLAGS" value="$(SYMBIAN_LD_MESSAGE_OPTION) $(BPABI_OPTION) $(RELOCATABLE_IMAGE_OPTION) $(UNRESOLVED_SYMBOL_REF_OPTION) $(STDLIB_OPTION) $(EXTRA_LD_OPTION) $(SYMBIAN_LINK_FLAGS.CONFIG) $(SYMBIAN_LINK_FLAGS.VAR)"/>
-		<set name="SYMBIAN_LINK_FLAGS.CONFIG" value=""/>
-		<set name="SYMBIAN_LINK_FLAGS.VAR" value=""/>
-		<set name="SYSTEMINCLUDE" value=""/>
-		<set name="TARGET" value=""/>
-		<set name="UNIX_SLASH_FOR_CC_ABS_PATHS" value="0"/>
-		<set name="UNRESOLVED_SYMBOL_REF_OPTION" value=""/>
-		<set name="DUMPBCINFO" value=""/>
-		<set name="MAKEDEFFILE" value="1"/>
-		<set name="PLATMACROS.WINDOWS" value="ARMCC EPOC32 MARM EABI GENERIC_MARM MARM_ARMV5 $(PLATMACROS.CONFIG) $(PLATMACROS.VAR)"/>
-		<set name="PLATMACROS.LINUX" value="$(PLATMACROS.WINDOWS)"/>
-		<set name="PLATMACROS.CONFIG" value=""/>
-		<set name="PLATMACROS.VAR" value=""/>
-		<set name="NO_UNALIGNED_ACCESS" value="$(CC.NO_UNALIGNED_ACCESS)"/>
-	</var>
-	<var name="v5">
-		<set name="TRADITIONAL_PLATFORM" value="ARMV5"/>
-		<set name="VARIANTPLATFORM" value="armv5"/>
-		<set name="PLATMACROS.CONFIG" value=""/>
-		<set name="DEBUG_FORMAT" value="$(CC.DWARF2)"/>
-		<set name="TARGET_ARCH_OPTION" value="$(CC.ARMV5)"/>
-		<set name="LINKER_ARCH_OPTION" value="$(LD.ARMV5)"/>
-		<set name="ARMFPU" value="$(CC.SOFTVFP_MAYBE_VFPV2)"/>
-		<set name="GENERATE_ABIV1_IMPLIBS" value="$(SUPPORTS_ABIV1_IMPLIBS)"/>
-	</var>
-	<var name="v6">
-		<set name="TRADITIONAL_PLATFORM" value="ARMV6"/>
-		<set name="VARIANTPLATFORM" value="armv6"/>
-		<set name="PLATMACROS.CONFIG" value="ARMV6"/>
-		<set name="ARMMACROS.CONFIG" value="__ARMV6__"/>
-		<set name="DEBUG_FORMAT" value="$(CC.DWARF2)"/>
-		<set name="TARGET_ARCH_OPTION" value="$(CC.ARMV6)"/>
-		<set name="LINKER_ARCH_OPTION" value="$(LD.ARMV6)"/>
-		<set name="STATIC_RUNTIME_DIR" value="$(EPOCROOT)/epoc32/release/armv5/$(VARIANTTYPE)"/>
-		<set name="ARMFPU" value="$(CC.SOFTVFP_MAYBE_VFPV2)"/>
-	</var>
-	<var name="v7">
-		<set name="TRADITIONAL_PLATFORM" value="ARMV7"/>
-		<set name="VARIANTPLATFORM" value="armv7"/>
-		<set name="PLATMACROS.CONFIG" value="ARMV7"/>
-		<set name="ARMMACROS.CONFIG" value="__ARMV7__"/>
-		<set name="DEBUG_FORMAT" value="$(CC.DWARF3)"/>
-		<set name="TARGET_ARCH_OPTION" value="$(CC.ARMV7)"/>
-		<set name="LINKER_ARCH_OPTION" value="$(LD.ARMV7)"/>
-		<set name="ARMFPU" value="$(CC.SOFTVFP_MAYBE_VFPV3)"/>
-	</var>
-	<var name="9e" extends="v5">
-		<set name="VARIANTPLATFORM" value="arm9e"/>
-		<set name="PLATMACROS.CONFIG" value="ARM9E"/>
-		<set name="ARMMACROS.CONFIG" value="__ARM9E__"/>
-		<set name="TARGET_ARCH_OPTION" value="--cpu ARM9E"/>
-		<set name="STATIC_RUNTIME_DIR" value="$(EPOCROOT)/epoc32/release/armv5/$(VARIANTTYPE)"/>
-	</var>
-
-	<alias name="armv5_urel" meaning="arm.v5.urel.rvct2_2"/>
-	<alias name="armv5_udeb" meaning="arm.v5.udeb.rvct2_2"/>
-	<!-- To switch to GCCE for building armv5 code, 
-	comment out the two lines above this comment
-	and comment in the two lines below this comment -->
-	<!-- <alias name="armv5_urel" meaning="arm.v5.urel.gcce4_3_2"/> -->
-	<!-- <alias name="armv5_udeb" meaning="arm.v5.udeb.gcce4_3_2"/> -->
-
-	<!-- These aliases are provided to work with the "gcce_armv5" group -->
-	<alias name="armv5_urel_gcce4_3_2" meaning="arm.v5.urel.gcce4_3_2"/>
-	<alias name="armv5_udeb_gcce4_3_2" meaning="arm.v5.udeb.gcce4_3_2"/>
-
-	<!-- GCCE 4.3.3 aliases -->
-	<alias name="armv5_urel_gcce4_3_3" meaning="arm.v5.urel.gcce4_3_3"/>
-	<alias name="armv5_udeb_gcce4_3_3" meaning="arm.v5.udeb.gcce4_3_3"/>
-	
-	<alias name="armv6_urel" meaning="arm.v6.urel.rvct2_2"/>
-	<alias name="armv6_udeb" meaning="arm.v6.udeb.rvct2_2"/>
-	<alias name="armv7_urel" meaning="arm.v7.urel.rvct3_1"/>
-	<alias name="armv7_udeb" meaning="arm.v7.udeb.rvct3_1"/>
-
-	<alias name="arm9e_urel" meaning="arm.9e.urel.rvct2_2"/>
-	<alias name="arm9e_udeb" meaning="arm.9e.udeb.rvct2_2"/>
-
-	<group name="armv5">
-		<aliasRef ref="armv5_urel"/>
-		<aliasRef ref="armv5_udeb"/>
-	</group>
-
-	<group name="armv6">
-		<aliasRef ref="armv6_urel"/>
-		<aliasRef ref="armv6_udeb"/>
-	</group>
-	<group name="armv7">
-		<aliasRef ref="armv7_urel"/>
-		<aliasRef ref="armv7_udeb"/>
-	</group>
-
-	<group name="arm9e">
-		<aliasRef ref="arm9e_urel"/>
-		<aliasRef ref="arm9e_udeb"/>
-	</group>
-	
-	<group name="gcce_armv5">
-		<aliasRef ref="armv5_urel_gcce4_3_2"/>
-		<aliasRef ref="armv5_udeb_gcce4_3_2"/>
-	</group>
-	
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- build variants for ARM toolchain builds -->
+	<var name="arm" extends="root">
+		<varRef ref="default.interfaces"/>
+		<varRef ref="default.locations"/>
+		
+		<!-- tools and scripts -->
+		<env name="BMCONV" default="$(EPOCROOT)/epoc32/tools/bmconv$(DOTEXE)" type="tool"/>
+		<env name="CHECKLIB" default="$(EPOCROOT)/epoc32/tools/checklib$(DOTEXE)" type="tool"/>
+		<env name="CPPFILT" default="$(GCCPREFIX)c++filt$(DOTEXE)" type="tool"/>
+		<env name="EFREEZE" default="$(PERL) $(EPOCROOT)/epoc32/tools/efreeze.pl" type="script"/>
+		<env name="ELF2E32" default="$(EPOCROOT)/epoc32/tools/elf2e32$(DOTEXE)" type="tool"/>
+		<env name="PREPDEF" default="$(PERL) $(EPOCROOT)/epoc32/tools/prepdef.pl" type="script"/>
+		<env name="RCOMP" default="$(EPOCROOT)/epoc32/tools/rcomp$(DOTEXE)" type="tool"/>
+		<!-- RANSLEEP is a program that can be used to cause a random delay in milliseconds. This is only useful in parallel builds. See the PERTURBSTARTTIME switch for more details.  -->
+		<env name="RANSLEEP" default="$(SBS_HOME)/bin/$(HOSTPLATFORM_DIR)/ransleep$(DOTEXE)" type="tool"/>
+		<env name="SBSV1MAKE" default="$(EPOCROOT)/epoc32/tools/make$(DOTEXE)" type="tool"/>
+		<env name="STRINGTABLE" default="$(PERL) $(EPOCROOT)/epoc32/tools/stringtable.pl" type="script"/>
+		<env name="TRANASM" default="$(PERL) $(EPOCROOT)/epoc32/tools/tranasm.pl" type="script"/>
+			
+		<!-- interfaces -->
+		<set name="INTERFACE.extension" value="Symbian.extension"/>
+		
+		<!-- macros -->
+		<set name="ARMMACROS.CONFIG" value=""/>
+		<set name="ARMMACROS.VAR" value=""/>
+		<set name="ARMMACROS" value="__MARM_ARMV5__ $(ARMMACROS.CONFIG) $(ARMMACROS.VAR)"/>
+		<set name="PLATMACROS.WINDOWS" value="$(PLATMACROS.TOOLCHAIN) EPOC32 MARM EABI GENERIC_MARM MARM_ARMV5 $(PLATMACROS.CONFIG) $(PLATMACROS.VAR)"/>
+		<set name="PLATMACROS.LINUX" value="$(PLATMACROS.WINDOWS)"/>
+		<set name="PLATMACROS.CONFIG" value=""/>
+		<set name="PLATMACROS.VAR" value=""/>
+		<set name="PLATMACROS.TOOLCHAIN" value=""/>
+		
+		<set name="BLDINF_OUTPUTPATH" value="$(SBS_BUILD_DIR)"/>
+		<set name="CAPABILITY" value=""/>
+		<set name="CDEFS" value="__SUPPORT_CPP_EXCEPTIONS__ _UNICODE __SYMBIAN32__ __EPOC32__ __MARM__ __EABI__ __PRODUCT_INCLUDE__=&quot;$(PRODUCT_INCLUDE)&quot; $(MMPDEFS) $(ARMMACROS)"/>
+		<set name="CODE_SEGMENT_START" value=""/>
+		<set name="DEFAULT_STDCPP_NEWLIB" value="stdnew.dso"/>
+		<set name="DEFAULT_SYMBIAN_NEWLIB" value="scppnwdl.dso"/>
+		<set name="DUMPBCINFO" value=""/>
+		<set name="EPOCSTACKSIZE" value=""/>
+		<set name="FULLVARIANTPATH" value="$(VARIANTPLATFORM)/$(VARIANTTYPE)"/>
+		<set name="HEADER_FILES_CONTROL_OPTION" value=""/>
+		<set name="LIBRARY_DEBUG" value=""/>
+		<set name="MMPDEFS" value=""/>
+		<set name="NMAKE" value="nmake"/>
+		<set name="NMAKEFLAGS" value="-nologo -x - "/>
+		<set name="NO_UNALIGNED_ACCESS" value="$(CC.NO_UNALIGNED_ACCESS)"/>
+		<set name="OUTPUTPATH" value="$(SBS_BUILD_DIR)"/>
+		<set name="PERTURBSTARTTIME" value=""/>
+		<!-- add a random delay before starting armcc or armlink to ease contention for licenses the maximum time to delay in milliseconds. RANSLEEP program must be available.   -->
+		<set name="PERTURBMSECS" value="500"/>
+		<!-- the maximum time to delay in milliseconds -->
+		<set name="POSTLINKER_COMPRESSION_DEFAULT" value="inflate"/>
+		<set name="RELEASEPATH" value="$(EPOCROOT)/epoc32/release"/>
+		<set name="RESOLVED_DEFFILE" value=""/>
+		<set name="RUNTIME_LIBS_PATH" value="$(EPOCROOT)/epoc32/release/armv5/lib"/>
+		<set name="SID" value=""/>
+		<set name="STATIC_LIBRARY_DIR" value="$(EPOCROOT)/epoc32/release/$(VARIANTPLATFORM)/$(VARIANTTYPE)"/>
+		<set name="STATIC_RUNTIME_DIR" value="$(EPOCROOT)/epoc32/release/$(VARIANTPLATFORM)/$(VARIANTTYPE)"/>
+		<set name="SYMBIAN_CC_MESSAGE_OPTION" value="$(CC_WARNINGS_CONTROL_OPTION) $(CC_ERRORS_CONTROL_OPTION)"/>
+		<set name="SYMBIAN_DLL_DEFINITION" value="__DLL__"/>
+		<set name="SYMBIAN_EXE_DEFINITION" value="__EXE__"/>
+		<set name="SYMBIAN_LINK_FLAGS" value="$(SYMBIAN_LD_MESSAGE_OPTION) $(BPABI_OPTION) $(RELOCATABLE_IMAGE_OPTION) $(UNRESOLVED_SYMBOL_REF_OPTION) $(STDLIB_OPTION) $(EXTRA_LD_OPTION) $(SYMBIAN_LINK_FLAGS.CONFIG) $(SYMBIAN_LINK_FLAGS.VAR)"/>
+		<set name="SYMBIAN_LINK_FLAGS.CONFIG" value=""/>
+		<set name="SYMBIAN_LINK_FLAGS.VAR" value=""/>
+		<set name="SYSTEMINCLUDE" value=""/>
+		<set name="TARGET" value=""/>
+		<set name="UNIX_SLASH_FOR_CC_ABS_PATHS" value="0"/>
+		<set name="UNRESOLVED_SYMBOL_REF_OPTION" value=""/>	
+	</var>
+	
+	<var name="v5">
+		<set name="TRADITIONAL_PLATFORM" value="ARMV5"/>
+		<set name="VARIANTPLATFORM" value="armv5"/>
+		<set name="DEBUG_FORMAT" value="$(CC.DWARF2)"/>
+		<set name="TARGET_ARCH_OPTION" value="$(CC.ARMV5)"/>
+		<set name="LINKER_ARCH_OPTION" value="$(LD.ARMV5)"/>
+		<set name="COMPILER_FPU_DEFAULT" value="$(CC.SOFTVFP_MAYBE_VFPV2)"/>
+		<set name="POSTLINKER_FPU_DEFAULT" value="$(PL.SOFTVFP_MAYBE_VFPV2)"/>
+	</var>
+	<var name="v6">
+		<set name="TRADITIONAL_PLATFORM" value="ARMV6"/>
+		<set name="VARIANTPLATFORM" value="armv6"/>
+		<set name="PLATMACROS.CONFIG" value="ARMV6"/>
+		<set name="ARMMACROS.CONFIG" value="__ARMV6__"/>
+		<set name="DEBUG_FORMAT" value="$(CC.DWARF2)"/>
+		<set name="TARGET_ARCH_OPTION" value="$(CC.ARMV6)"/>
+		<set name="LINKER_ARCH_OPTION" value="$(LD.ARMV6)"/>
+		<set name="STATIC_RUNTIME_DIR" value="$(EPOCROOT)/epoc32/release/armv5/$(VARIANTTYPE)"/>
+		<set name="COMPILER_FPU_DEFAULT" value="$(CC.SOFTVFP_MAYBE_VFPV2)"/>
+		<set name="POSTLINKER_FPU_DEFAULT" value="$(PL.SOFTVFP_MAYBE_VFPV2)"/>
+		<set name="SUPPORTS_ABIV1_IMPLIBS" value=""/>
+	</var>
+	<var name="v7">
+		<set name="TRADITIONAL_PLATFORM" value="ARMV7"/>
+		<set name="VARIANTPLATFORM" value="armv7"/>
+		<set name="PLATMACROS.CONFIG" value="ARMV7"/>
+		<set name="ARMMACROS.CONFIG" value="__ARMV7__"/>
+		<set name="DEBUG_FORMAT" value="$(CC.DWARF3)"/>
+		<set name="TARGET_ARCH_OPTION" value="$(CC.ARMV7)"/>
+		<set name="LINKER_ARCH_OPTION" value="$(LD.ARMV7)"/>
+		<set name="COMPILER_FPU_DEFAULT" value="$(CC.SOFTVFP_MAYBE_VFPV3)"/>
+		<set name="POSTLINKER_FPU_DEFAULT" value="$(PL.SOFTVFP_MAYBE_VFPV3)"/>
+		<set name="SUPPORTS_ABIV1_IMPLIBS" value=""/>
+	</var>
+	<var name="9e" extends="v5">
+		<set name="VARIANTPLATFORM" value="arm9e"/>
+		<set name="PLATMACROS.CONFIG" value="ARM9E"/>
+		<set name="ARMMACROS.CONFIG" value="__ARM9E__"/>
+		<set name="TARGET_ARCH_OPTION" value="--cpu ARM9E"/>
+		<set name="STATIC_RUNTIME_DIR" value="$(EPOCROOT)/epoc32/release/armv5/$(VARIANTTYPE)"/>
+	</var>
+
+	<alias name="armv5_urel" meaning="arm.v5.urel.rvct2_2"/>
+	<alias name="armv5_udeb" meaning="arm.v5.udeb.rvct2_2"/>
+	<!-- To switch to GCCE for building armv5 code, 
+	comment out the two lines above this comment
+	and comment in the two lines below this comment -->
+	<!-- <alias name="armv5_urel" meaning="arm.v5.urel.gcce4_3_2"/> -->
+	<!-- <alias name="armv5_udeb" meaning="arm.v5.udeb.gcce4_3_2"/> -->
+
+	<!-- These aliases are provided to work with the "gcce_armv5" group -->
+	<alias name="armv5_urel_gcce4_3_2" meaning="arm.v5.urel.gcce4_3_2"/>
+	<alias name="armv5_udeb_gcce4_3_2" meaning="arm.v5.udeb.gcce4_3_2"/>
+
+	<!-- GCCE 4.3.3 aliases -->
+	<alias name="armv5_urel_gcce4_3_3" meaning="arm.v5.urel.gcce4_3_3"/>
+	<alias name="armv5_udeb_gcce4_3_3" meaning="arm.v5.udeb.gcce4_3_3"/>
+
+	<alias name="armv5_urel_gcce4_4_1" meaning="arm.v5.urel.gcce4_4_1"/>
+	<alias name="armv5_udeb_gcce4_4_1" meaning="arm.v5.udeb.gcce4_4_1"/>
+	
+	<alias name="armv6_urel" meaning="arm.v6.urel.rvct2_2"/>
+	<alias name="armv6_udeb" meaning="arm.v6.udeb.rvct2_2"/>
+	<alias name="armv7_urel" meaning="arm.v7.urel.rvct3_1"/>
+	<alias name="armv7_udeb" meaning="arm.v7.udeb.rvct3_1"/>
+
+	<alias name="arm9e_urel" meaning="arm.9e.urel.rvct2_2"/>
+	<alias name="arm9e_udeb" meaning="arm.9e.udeb.rvct2_2"/>
+
+	<group name="armv5">
+		<aliasRef ref="armv5_urel"/>
+		<aliasRef ref="armv5_udeb"/>
+	</group>
+
+	<group name="armv6">
+		<aliasRef ref="armv6_urel"/>
+		<aliasRef ref="armv6_udeb"/>
+	</group>
+	<group name="armv7">
+		<aliasRef ref="armv7_urel"/>
+		<aliasRef ref="armv7_udeb"/>
+	</group>
+
+	<group name="arm9e">
+		<aliasRef ref="arm9e_urel"/>
+		<aliasRef ref="arm9e_udeb"/>
+	</group>
+	
+	<group name="gcce_armv5">
+		<aliasRef ref="armv5_urel_gcce4_3_2"/>
+		<aliasRef ref="armv5_udeb_gcce4_3_2"/>
+	</group>
+	
+</build>
--- a/sbsv2/raptor/lib/config/build.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/build.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,8 +1,8 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- Configuration for metadata processing  -->
-
-	<var name="build">
-		<varRef ref="default.locations"/>
-	</var>
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- Configuration for metadata processing  -->
+
+	<var name="build">
+		<varRef ref="default.locations"/>
+	</var>
+</build>
--- a/sbsv2/raptor/lib/config/carbide.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/carbide.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,37 +1,53 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build build/666.xsd">
-
-	<!-- This file is for Carbide to get a list of buildable configurations.
-	
-		The config elements are from the old 1.0 schema but the file has
-		an invalid schema version which forces the Raptor XML parser to
-		ignore it.
-		
-		This is an interim measure until a formal API is agreed. -->
-	
-	<config name="arm" abstract="true">
-		<config name="armv5" abstract="true">
-			<config name="armv5_urel"/>
-			<config name="armv5_udeb"/>
-		</config>
-		<config name="armv6" abstract="true">
-			<config name="armv6_urel"/>
-			<config name="armv6_udeb"/>
-		</config>
-		<config name="armv7" abstract="true">
-			<config name="armv7_urel"/>
-			<config name="armv7_udeb"/>
-		</config>
-		<config name="armv9e" abstract="true">
-			<config name="armv9e_urel"/>
-			<config name="armv9e_udeb"/>
-		</config>
-	</config>
-
-	<config name="winscw" abstract="true">
-		<config name="winscw_urel"/>
-		<config name="winscw_udeb"/>
-	</config>
-
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build build/666.xsd">
+
+	<!-- This file is for Carbide to get a list of buildable configurations.
+	
+		The config elements are from the old 1.0 schema but the file has
+		an invalid schema version which forces the Raptor XML parser to
+		ignore it.
+		
+		This is an interim measure until a formal API is agreed. -->
+	
+	<config name="arm" abstract="true">
+		<config name="armv5" abstract="true">
+			<config name="armv5_urel"/>
+			<config name="armv5_udeb"/>
+		</config>
+		<config name="armv6" abstract="true">
+			<config name="armv6_urel"/>
+			<config name="armv6_udeb"/>
+		</config>
+		<config name="armv7" abstract="true">
+			<config name="armv7_urel"/>
+			<config name="armv7_udeb"/>
+		</config>
+		<config name="armv9e" abstract="true">
+			<config name="armv9e_urel"/>
+			<config name="armv9e_udeb"/>
+		</config>
+		<config name="armv5_gcce" abstract="true">
+			<config name="armv5_urel_gcce"/>
+			<config name="armv5_udeb_gcce"/>
+		</config>
+		<config name="armv6_gcce" abstract="true">
+			<config name="armv6_urel_gcce"/>
+			<config name="armv6_udeb_gcce"/>
+		</config>
+		<config name="armv7_gcce" abstract="true">
+			<config name="armv7_urel_gcce"/>
+			<config name="armv7_udeb_gcce"/>
+		</config>
+		<config name="armv9e_gcce" abstract="true">
+			<config name="armv9e_urel_gcce"/>
+			<config name="armv9e_udeb_gcce"/>
+		</config>
+	</config>
+
+	<config name="winscw" abstract="true">
+		<config name="winscw_urel"/>
+		<config name="winscw_udeb"/>
+	</config>
+
+</build>
--- a/sbsv2/raptor/lib/config/coverity.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/coverity.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,10 +1,10 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-
-
-	<!-- Coverity testing -->
-	<var name="coverity">
-		<prepend name='CC' value='D:/apps/Coverity/bin/cov-translate.exe --run-compile '/>
-	</var>
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+
+
+	<!-- Coverity testing -->
+	<var name="coverity">
+		<prepend name='CC' value='D:/apps/Coverity/bin/cov-translate.exe --run-compile '/>
+	</var>
+</build>
--- a/sbsv2/raptor/lib/config/default.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/default.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,32 +1,32 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-
-	<!-- The build configurations built by default -->
-
-	<group name="default">
-		<groupRef ref="armv5"/>
-		<groupRef ref="winscw"/>
-	</group>
-
-	<group name="urel">
-		<aliasRef ref="armv5_urel"/>
-		<aliasRef ref="winscw_urel"/>
-	</group>
-
-	<group name="udeb">
-		<aliasRef ref="armv5_udeb"/>
-		<aliasRef ref="winscw_udeb"/>
-	</group>
-
-	<!-- all known configurations -->
-
-	<group name="all">
-		<groupRef ref="armv5"/>
-		<groupRef ref="armv7"/>
-		<groupRef ref="gccxml"/>
-		<groupRef ref="tools"/>
-		<groupRef ref="tools2"/>
-		<groupRef ref="winscw"/>
-	</group>
-
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+
+	<!-- The build configurations built by default -->
+
+	<group name="default">
+		<groupRef ref="armv5"/>
+		<groupRef ref="winscw"/>
+	</group>
+
+	<group name="urel">
+		<aliasRef ref="armv5_urel"/>
+		<aliasRef ref="winscw_urel"/>
+	</group>
+
+	<group name="udeb">
+		<aliasRef ref="armv5_udeb"/>
+		<aliasRef ref="winscw_udeb"/>
+	</group>
+
+	<!-- all known configurations -->
+
+	<group name="all">
+		<groupRef ref="armv5"/>
+		<groupRef ref="armv7"/>
+		<groupRef ref="gccxml"/>
+		<groupRef ref="tools"/>
+		<groupRef ref="tools2"/>
+		<groupRef ref="winscw"/>
+	</group>
+
+</build>
--- a/sbsv2/raptor/lib/config/gcc.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/gcc.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,106 +1,106 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-
-	<!-- build configurations for GCC compilers -->
-	<var name="tools2_base" extends="root">
-
-		<varRef ref="default.interfaces"/>
-		<varRef ref="default.locations"/>
-		<!-- picked up from the Environment -->
-		<env name='RANLIB' default='$(GCCPREFIX)ranlib$(DOTEXE)' type='tool'/>
-		<env name='GCC' default='$(GCCPREFIX)g++$(DOTEXE)' type='tool'/>
-		<env name='AR' default='$(GCCPREFIX)ar$(DOTEXE)' type='tool'/>
-
-		<!-- interfaces -->
-		<set name="INTERFACE.exe" value="Tools.exe"/>
-		<set name="INTERFACE.lib" value="Tools.lib"/>
-
-		<!-- Java used by Trace Compiler -->
-		<env name='JAVA_HOME' default='' type='path'/>
-		<env name='JAVATC' default='$(JAVA_HOME)/bin/java' type='tool'/>
-
-		<!-- link to bld.inf and mmp platform names -->
-		<set name='TRADITIONAL_PLATFORM' value='TOOLS2'/>
-		<set name='VARIANTPLATFORM' value='tools2'/>
-
-		<!-- used by FLM code -->
-		<set name='COMPILER' value='$(GCC) -c' type='tool' versionCommand='$(GCC) -v' versionResult='gcc version (3.[456])|(4.[0-9])'/>
-
-		<set name='CFLAGS' value='-fdefer-pop -fmerge-constants -fthread-jumps -floop-optimize -fif-conversion -fif-conversion2 -fguess-branch-probability -fcprop-registers -foptimize-sibling-calls -fstrength-reduce -fcse-follow-jumps -fcse-skip-blocks -frerun-cse-after-loop -frerun-loop-opt -fgcse -fgcse-lm -fgcse-sm -fgcse-las -fdelete-null-pointer-checks -fexpensive-optimizations -fregmove -fschedule-insns -fschedule-insns2 -fsched-interblock -fsched-spec -fcaller-saves -fpeephole2 -freorder-blocks -freorder-functions -fstrict-aliasing -funit-at-a-time -falign-functions -falign-jumps -falign-loops -falign-labels -fcrossjumping -pipe -Wall -Wno-ctor-dtor-privacy -Wno-unknown-pragmas -m32'/>
-
-		<!-- msys based programs sometimes don't search the path properly.
-		COMPILER_PATH can be set to tell gcc where to find
-		as.exe (sometimes it doesn't and a build step fails).
-		-->
-		<set name='COMPILER_PATH.WIN32' value='$(SBS_HOME)/win32/mingw/bin'/>
-		<set name='COMPILER_PATH.LINUX' value=''/>
-
-		<set name='CFLAGS.WIN32' value=''/>
-
-		<!-- macro definitions set by mmps etc -->
-		<set name='CDEFS' value='$(MMPDEFS)'/>
-
-
-		<set name='CDEFS.DEFAULT' value='__SYMBIAN32__ __TOOLS__ __TOOLS2__ __EXE__ __SUPPORT_CPP_EXCEPTIONS__ __PRODUCT_INCLUDE__="$(PRODUCT_INCLUDE)"'/>
-		<set name='CDEFS.WIN32' value='$(CDEFS.DEFAULT) _WIN32 WIN32 _WINDOWS __TOOLS2_WINDOWS__'/>
-		<set name='CDEFS.LINUX' value='$(CDEFS.DEFAULT) __LINUX__ __TOOLS2_LINUX__'/>
-
-		<set name='INC.COMPILER' value='$(EPOCINCLUDE)/gcc_mingw/gcc_mingw_3_4_2.h'/>
-
-		<set name='OPT.D' value='-D'/>
-		<set name='OPT.L' value='-L'/>
-		<set name='OPT.l' value='-l'/>
-		<set name='OPT.O' value='-o '/>
-		<set name='OPT.PREINCLUDE' value='-include '/>
-		<set name='OPT.SYSTEMINCLUDE' value='-isystem '/>
-		<set name='OPT.USERINCLUDE' value='-I '/>
-
-		<!-- always use stlport headers -->
-		<set name='SYSTEMINCLUDE' value='$(EPOCINCLUDE)/tools/stlport'/>
-
-		<set name='LINKER' value='$(GCC)'/>
-		<set name='LFLAGS' value=''/>
-		<set name='STATICLIBRARY' value='stlport.5.1'/>
-		<set name='LIBS' value=''/>
-		<set name='LIBS.WIN32' value='$(LIBS)'/>
-		<set name='LIBS.LINUX' value='$(LIBS) pthread'/>
-
-		<set name='PLATMACROS.WINDOWS' value='GCC32 TOOLS2 TOOLS2_WINDOWS'/>
-		<set name='PLATMACROS.LINUX' value='GCC32 TOOLS2 TOOLS2_LINUX'/>
-
-		<set name='ARCHIVER' value='$(AR)'/>
-		<set name='AFLAGS' value='cr'/>
-
-		<set name='MMPDEFS' value=''/>
-		<set name='TARGET' value=''/>
-		<set name='TARGETTYPE' value=''/>
-		<set name='BLDINF_OUTPUTPATH' value='$(SBS_BUILD_DIR)'/>
-
-		<set name='OUTPUTPATH' value='$(SBS_BUILD_DIR)'/>
-		<set name='RELEASEPATH' value='$(EPOCROOT)/epoc32/release/tools2$$(TOOLPLATFORMDIR)'/>
-	</var>
-
-	<var name="tools2_deb" extends="tools2_base">
-		<set name='TOOLSPATH' value=''/> <!-- do not install -->
-		<set name='VARIANTTYPE' value='deb'/>
-
-		<append name='CFLAGS' value='-g'/>
-		<append name='CDEFS' value='_DEBUG'/>
-		<append name='RELEASEPATH' value='/deb' separator=''/>
-	</var>
-
-	<var name="tools2_rel" extends="tools2_base">
-		<set name='TOOLSPATH' value='$(EPOCTOOLS)'/> <!-- install -->
-		<set name='VARIANTTYPE' value='rel'/>
-
-		<append name='CFLAGS' value='-s'/>
-		<append name='CDEFS' value='NDEBUG'/>
-		<append name='RELEASEPATH' value='/rel' separator=''/>
-	</var>
-
-	<group name="tools2">
-		<varRef ref='tools2_rel'/>
-		<varRef ref='tools2_deb'/>
-	</group>
-
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- build variants for GCC toolchains -->
+	<var name="tools2_base" extends="root">
+		<varRef ref="default.interfaces"/>
+		<varRef ref="default.locations"/>
+		
+		<!-- toolchain tools -->
+		<env name='RANLIB' default='$(GCCPREFIX)ranlib$(DOTEXE)' type='tool'/>
+		<env name='GCC' default='$(GCCPREFIX)g++$(DOTEXE)' type='tool'/>
+		<env name='AR' default='$(GCCPREFIX)ar$(DOTEXE)' type='tool'/>
+		
+		<set name='COMPILER' value='$(GCC) -c' type='tool' versionCommand='$(GCC) -v' versionResult='gcc version (3.[456])|(4.[0-9])'/>
+		<set name='LINKER' value='$(GCC)'/>
+
+		<!-- tools and scripts -->
+		<env name='JAVATC' default='$(JAVA_HOME)/bin/java' type='tool'/> <!-- Java used by Trace Compiler -->
+
+		<!-- interfaces -->
+		<set name="INTERFACE.exe" value="Tools.exe"/>
+		<set name="INTERFACE.lib" value="Tools.lib"/>
+
+		<!-- link to bld.inf and mmp platform names -->
+		<set name='TRADITIONAL_PLATFORM' value='TOOLS2'/>
+
+		<!-- Java used by Trace Compiler -->
+		<set name='CFLAGS' value='-fdefer-pop -fmerge-constants -fthread-jumps -floop-optimize -fif-conversion -fif-conversion2 -fguess-branch-probability -fcprop-registers -foptimize-sibling-calls -fstrength-reduce -fcse-follow-jumps -fcse-skip-blocks -frerun-cse-after-loop -frerun-loop-opt -fgcse -fgcse-lm -fgcse-sm -fgcse-las -fdelete-null-pointer-checks -fexpensive-optimizations -fregmove -fschedule-insns -fschedule-insns2 -fsched-interblock -fsched-spec -fcaller-saves -fpeephole2 -freorder-blocks -freorder-functions -fstrict-aliasing -funit-at-a-time -falign-functions -falign-jumps -falign-loops -falign-labels -fcrossjumping -pipe -Wall -Wno-ctor-dtor-privacy -Wno-unknown-pragmas -m32'/>
+		<env name='JAVA_HOME' default='' type='path'/>		
+		<set name='VARIANTPLATFORM' value='tools2'/>
+
+		<!-- msys based programs sometimes don't search the path properly.
+		COMPILER_PATH can be set to tell gcc where to find
+		as.exe (sometimes it doesn't and a build step fails).
+		-->
+		<set name='COMPILER_PATH.WIN32' value='$(SBS_HOME)/win32/mingw/bin'/>
+		<set name='COMPILER_PATH.LINUX' value=''/>
+
+		<set name='CFLAGS.WIN32' value=''/>
+
+		<!-- macro definitions set by mmps etc -->
+		<set name='CDEFS' value='$(MMPDEFS)'/>
+		<set name='CDEFS.DEFAULT' value='__SYMBIAN32__ __TOOLS__ __TOOLS2__ __EXE__ __SUPPORT_CPP_EXCEPTIONS__ __PRODUCT_INCLUDE__="$(PRODUCT_INCLUDE)"'/>
+		<set name='CDEFS.WIN32' value='$(CDEFS.DEFAULT) _WIN32 WIN32 _WINDOWS __TOOLS2_WINDOWS__'/>
+		<set name='CDEFS.LINUX' value='$(CDEFS.DEFAULT) __LINUX__ __TOOLS2_LINUX__'/>
+
+		<set name='INC.COMPILER' value='$(EPOCINCLUDE)/gcc_mingw/gcc_mingw_3_4_2.h'/>
+
+		<set name='OPT.D' value='-D'/>
+		<set name='OPT.L' value='-L'/>
+		<set name='OPT.l' value='-l'/>
+		<set name='OPT.O' value='-o '/>
+		<set name='OPT.PREINCLUDE' value='-include '/>
+		<set name='OPT.SYSTEMINCLUDE' value='-isystem '/>
+		<set name='OPT.USERINCLUDE' value='-I '/>
+
+		<!-- always use stlport headers -->
+		<set name='SYSTEMINCLUDE' value='$(EPOCINCLUDE)/tools/stlport'/>
+
+		<set name='LFLAGS' value=''/>
+		<set name='STATICLIBRARY' value='stlport.5.1'/>
+		<set name='LIBS' value=''/>
+		<set name='LIBS.WIN32' value='$(LIBS)'/>
+		<set name='LIBS.LINUX' value='$(LIBS) pthread'/>
+
+		<set name='PLATMACROS.WINDOWS' value='GCC32 TOOLS2 TOOLS2_WINDOWS'/>
+		<set name='PLATMACROS.LINUX' value='GCC32 TOOLS2 TOOLS2_LINUX'/>
+
+		<set name='ARCHIVER' value='$(AR)'/>
+		<set name='AFLAGS' value='cr'/>
+
+		<set name='MMPDEFS' value=''/>
+		<set name='TARGET' value=''/>
+		<set name='TARGETTYPE' value=''/>
+		<set name='BLDINF_OUTPUTPATH' value='$(SBS_BUILD_DIR)'/>
+
+		<set name='OUTPUTPATH' value='$(SBS_BUILD_DIR)'/>
+		<set name='RELEASEPATH' value='$(EPOCROOT)/epoc32/release/tools2' host='win.*'/>
+		<set name='RELEASEPATH' value='$(EPOCROOT)/epoc32/release/tools2/$(HOSTPLATFORM_DIR)' host='lin.*'/>
+	</var>
+
+	<var name="t_deb">
+		<set name='TOOLSPATH' value=''/> <!-- do not install -->
+		<set name='VARIANTTYPE' value='deb'/>
+
+		<append name='CFLAGS' value='-g'/>
+		<append name='CDEFS' value='_DEBUG'/>
+		<append name='RELEASEPATH' value='/deb' separator=''/>
+	</var>
+	<alias name="tools2_deb" meaning="tools2_base.t_deb"/>
+	
+	<var name="t_rel">
+		<set name='TOOLSPATH' value='$(EPOCTOOLS)'/> <!-- install -->
+		<set name='VARIANTTYPE' value='rel'/>
+
+		<append name='CFLAGS' value='-s'/>
+		<append name='CDEFS' value='NDEBUG'/>
+		<append name='RELEASEPATH' value='/rel' separator=''/>
+	</var>
+	<alias name="tools2_rel" meaning="tools2_base.t_rel"/>
+	
+	<group name="tools2">
+		<aliasRef ref='tools2_rel'/>
+		<aliasRef ref='tools2_deb'/>
+	</group>
+
+</build>
--- a/sbsv2/raptor/lib/config/gcce.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/gcce.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,108 +1,128 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- GCCE build variant for ARM compilers -->
-	<!-- This is called gcce_base in case someone wants to use "gcce" as a configuration name -->
-	<var name="gcce_base">
-		<set name="TOOLCHAIN" value="GCCE"/>
-		<set name="CC" value="$(GCCECC)"/>
-		<set name="LD" value="$(GCCELD)"/>
-		<set name="ASM" value="$(GCCEASM)"/>
-		<set name="AR" value="$(GCCEAR)"/>		
-		<set name="GCCECC" value="$(GCCEBIN)/arm-none-symbianelf-g++$(DOTEXE)"/>
-		<set name="GCCELD" value="$(GCCEBIN)/arm-none-symbianelf-ld$(DOTEXE)"/>
-		<set name="GCCEASM" value="$(GCCEBIN)/arm-none-symbianelf-as$(DOTEXE)"/>
-		<set name="GCCEAR" value="$(GCCEBIN)/arm-none-symbianelf-ar$(DOTEXE)"/>
-		<set name="FROMELF" value="$(GCCEBIN)/arm-none-symbianelf-readelf$(DOTEXE)"/>
-		<set name="AAPCS_OPTION" value="-mapcs -mthumb-interwork"/>
-		<set name="ARCHIVER_CREATE_OPTION" value="cr"/>
-		<set name="ARM_INSTRUCTION_SET" value="-marm"/>
-		<set name="ASM_OUTPUT_OPTION" value="-o"/>
-		<set name="ASSEMBLER_LISTING_OPTION" value="-S"/>
-		<set name="BPABI_OPTION" value=""/>
-		<set name="CC_ERRORS_CONTROL_OPTION" value=""/>
-		<set name="CC_WARNINGS_CONTROL_OPTION" value="-Wall -Wno-unknown-pragmas"/>
-		<set name="C_LANG_OPTION" value="-x c"/>
-		<set name="COMMANDFILE_OPTION" value="@"/>
-		<set name="COMPILE_ONLY_OPTION" value="-c"/>
-		<set name="CPP_LANG_OPTION" value="-x c++ -Wno-ctor-dtor-privacy"/>
-		<set name="DEBUG_OPTIMISATION" value="-O0"/>
-		<set name="DEPEND_OPTION" value="-MD -MF"/>
-		<set name="ENUM_OPTION" value=""/>
-		<set name="EXPORT_VTBL_OPTION" value=""/>
-		<set name="EXTRA_LD_OPTION" value=""/>
-		<set name="FPMODE_OPTION" value=""/>
-		<set name="LD_ERRORS_CONTROL_OPTION" value=""/>
-		<set name="LD_WARNINGS_CONTROL_OPTION" value="--no-undefined"/>
-		<set name="LISTING_OPTION" value="-S"/>
-		<set name="EXCEPTIONS" value="-fexceptions"/>
-		<set name="NO_EXCEPTIONS" value="-fno-exceptions"/>
-		<set name="PREINCLUDE_OPTION" value="-include"/>
-		<set name="PREPROCESSOR_OPTION" value="-E"/>
-		<set name="REL_OPTIMISATION" value="-O2"/>
-		<set name="STDLIB_OPTION" value="-nostdlib"/>
-		<set name="RUNTIME_SYMBOL_VISIBILITY_OPTION" value=""/>
-		<set name="RW_BASE_OPTION" value="-Tdata"/>
-		<set name="CODE_SEGMENT_START" value="-Ttext"/>
-		<set name="PREINCLUDE" value="$(EPOCINCLUDE)/gcce/gcce.h"/>
-		<!-- From the GCC manual: "With this option, GCC uses features of DWARF version 3 when they are useful; ..." -->
-		<!-- There is no -gdwarf-3 option; hence CC.DWARF2 and CC.DWARF3 have the same value. -->
-		<set name="CC.DWARF2" value="-gdwarf-2"/>
-		<set name="CC.DWARF3" value="-gdwarf-2"/>
-		<set name="LD.ARMV5" value=""/>
-		<set name="LD.ARMV6" value=""/>
-		<set name="LD.ARMV7" value=""/>
-		<set name="ARMMACROS.VAR" value=""/>
-		<set name="CFLAGS" value=""/>
-		<set name="CIADEFS" value="__CIA__"/>
-		<append name="CDEFS" value='__SUPPORT_CPP_EXCEPTIONS__ _UNICODE __SYMBIAN32__ __GCCE__ __EPOC32__ __MARM__ __EABI__ __PRODUCT_INCLUDE__="$(PRODUCT_INCLUDE)" $(MMPDEFS) $(ARMMACROS)'/>
-		<!-- Note that the intention of ABLD for CIA compilation seems to be "-S -Wa,-adln", although this doesn't work -->
-		<set name="COMPILER_CIA_FLAGS" value="-marm"/>
-		<set name="COMPILER_DEFINES" value="-D__GCCE__"/>
-		<set name="COMPILER_FPU_FLAGS" value="$(CC.OPT.SOFTVFP_MAYBE_VFPV2)$(CC.VAL.SOFTVFP_MAYBE_VFPV2)"/>		
-		<set name="COMPILER_INTERWORK_DEFINES" value="__MARM_INTERWORK__"/>
-		<set name="COMPILER_SYSTEM_INCLUDE_OPTION" value="-I"/>
-		<set name="COMPILER_THUMB_DEFINES" value="__MARM_THUMB__"/>
-		<set name="DATA_SEGMENT_START" value="$(SPLIT_OPTION) $(RW_BASE_OPTION)"/>
-		<set name="EXTRA_CC_OPTION" value=""/>
-		<set name="HEADER_FILES_CONTROL_OPTION" value=""/>
-		<set name="LIBPATH" value=""/>
-		<set name="LIBRARY" value=""/>
-		<set name="LICENSERETRY_OPTION" value=""/>
-		<set name="LINKER_ADD_STATIC_RUNTIME" value="1"/>
-		<set name="LINKER_DEBUG_OPTION" value=""/>
-		<!-- Clearly the linker libs stuff following isn't right - need to use ARMLIBS (or reinvent this a bit) -->
-		<set name="LINKER_DEFAULT_LIBS" value="-lsupc++ -lgcc"/>
-		<set name="LINKER_DEFAULT_LIB_PATHS" value="-L $(GCCEBIN)/../lib/gcc/arm-none-symbianelf/$(TOOLCHAINVERSION) -L $(GCCEBIN)/../lib/gcc/arm-none-symbianelf/$(TOOLCHAINVERSION)/../../../../arm-none-symbianelf/lib"/>
-		<set name="LINKER_ENTRY_OPTION" value="--entry"/>
-		<set name="LINKER_GROUP_START_OPTION" value="--start-group"/>
-		<set name="LINKER_GROUP_END_OPTION" value="--end-group"/>
-		<set name="LINKER_MISC_FLAGS" value="$(CODE_SEGMENT_START) 0x8000"/>
-		<set name="LINKER_NODEBUG_OPTION" value = "--strip-debug"/>
-		<set name="LINKER_SCRIPT_FILE_OPTION" value="-T"/>
-		<set name="LINKER_SYMBOLS_OPTION" value="-Map"/>
-		<set name="LINKER_SYMBOLS_FILE_OPTION" value=""/>
-		<set name="SHARED_OBJECT_OPTION" value="-shared"/>
-		<set name="SID" value=""/>
-		<set name="SO_NAME_OPTION" value="-soname"/>
-		<set name="STATIC_LIBS_PATH" value="" />
-		<set name="STDCPP_INCLUDE" value="$(EPOCINCLUDE)/stdapis"/>
-		<set name="SUPPORTS_ABIV1_IMPLIBS" value=""/>	
-		<set name="SYMBIAN_LD_MESSAGE_OPTION" value="$(LD_WARNINGS_CONTROL_OPTION) $(LD_ERRORS_CONTROL_OPTION)"/>
-		<set name="TARGET_RELOCATION_OPTION" value="--target1-rel" />
-		<set name="SYMVER_OPTION" value="--default-symver"/>
-		<set name="TEMP_FILES_OPTION" value="-pipe"/>
-		<set name="THUMB_INSTRUCTION_SET" value="-mthumb"/>
-		<set name="TRANSFORM_CIA" value=""/>		
-		<set name="INSTRUCTION_SET" value=""/>
-		<set name="UNDEFINED_SYMBOL_REF_OPTION" value="-u"/>
-		<set name="UNRESOLVED_SYMBOL_REF_OPTION" value=""/>
-		<set name="USERINCLUDE" value=""/>
-		<set name="USER_LIBS_PATH_OPTION" value="--userlibpath"/>
-		<set name="VFE_OPTION" value=""/>
-		<set name="PLATMACROS.WINDOWS" value="GCCE EPOC32 MARM EABI GENERIC_MARM MARM_ARMV5 $(PLATMACROS.CONFIG) $(PLATMACROS.VAR)"/>
-		<set name="PLATMACROS.LINUX" value="$(PLATMACROS.WINDOWS)"/>
-		<set name="PLATMACROS.CONFIG" value=""/>
-		<set name="PLATMACROS.VAR" value=""/>
-		<set name="NO_UNALIGNED_ACCESS" value="$(CC.NO_UNALIGNED_ACCESS)"/>
-	</var>
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- build variant for GCCE ARM toolchains -->
+	<var name="gcce_base">
+		<set name="TOOLCHAIN" value="GCCE"/>
+		<set name="PLATMACROS.TOOLCHAIN" value="GCCE"/>
+
+		<!-- toolchain tools -->
+		<set name="GCCEAR" value="$(GCCEBIN)/arm-none-symbianelf-ar$(DOTEXE)"/>
+		<set name="GCCEASM" value="$(GCCEBIN)/arm-none-symbianelf-as$(DOTEXE)"/>
+		<set name="GCCECC" value="$(GCCEBIN)/arm-none-symbianelf-g++$(DOTEXE)"/>
+		<set name="GCCELD" value="$(GCCEBIN)/arm-none-symbianelf-g++$(DOTEXE)"/>
+		<set name="FROMELF" value="$(GCCEBIN)/arm-none-symbianelf-readelf$(DOTEXE)"/>
+
+		<set name="CC" value="$(GCCECC)"/>
+		<set name="LD" value="$(GCCELD)"/>
+		<set name="ASM" value="$(GCCEASM)"/>
+		<set name="AR" value="$(GCCEAR)"/>
+		
+		<set name="AAPCS_OPTION" value="-mapcs -mthumb-interwork"/>
+		<set name="ARCHIVER_CREATE_OPTION" value="cr"/>
+		<set name="ARM_INSTRUCTION_SET" value="-marm"/>
+		<set name="ARMLIBS" value=""/>
+		<set name="ASM_OUTPUT_OPTION" value="-o"/>
+		<set name="ASSEMBLER_LISTING_OPTION" value="-S"/>
+		<set name="BPABI_OPTION" value=""/>
+		<set name="C_LANG_OPTION" value="-x c"/>
+		<set name="CC.ARMV5" value="-march=armv5t"/>
+		<set name="CC.ARMV6" value="-march=armv6t2"/>
+		<set name="CC.ARMV7" value="-march=armv7"/>
+		<!-- From the GCC manual: "With this option, GCC uses features of DWARF version 3 when they are useful; ..." -->
+		<!-- There is no -gdwarf-3 option; hence CC.DWARF2 and CC.DWARF3 have the same value. -->
+		<set name="CC.DWARF2" value="-gdwarf-2"/>
+		<set name="CC.DWARF3" value="-gdwarf-2"/>
+		<set name="CC.NO_UNALIGNED_ACCESS" value=""/>
+		<set name="CC.SOFTVFP_MAYBE_VFPV2" value="soft"/>
+		<set name="CC.SOFTVFP_MAYBE_VFPV3" value="soft"/>
+		<set name="CC_ERRORS_CONTROL_OPTION" value=""/>
+		<set name="CC_WARNINGS_CONTROL_OPTION" value="-Wall -Wno-unknown-pragmas"/>
+		<set name="CFLAGS" value=""/>
+		<set name="CIADEFS" value="__CIA__"/>
+		<set name="CODE_SEGMENT_START" value="-Ttext"/>
+		<set name="COMMANDFILE_OPTION" value="@"/>
+		<set name="COMPILE_ONLY_OPTION" value="-c"/>
+		<set name="COMPILER_CIA_FLAGS" value="-marm"/>
+		<set name="COMPILER_DEFINES" value="-D__GCCE__"/>		
+		<set name="COMPILER_FPU_OPTION" value="-mfloat-abi="/>		
+		<set name="COMPILER_INTERWORK_DEFINES" value="__MARM_INTERWORK__"/>
+		<set name="COMPILER_SYSTEM_INCLUDE_OPTION" value="-I"/>
+		<set name="COMPILER_THUMB_DEFINES" value="__MARM_THUMB__"/>
+		<set name="CPP_LANG_OPTION" value="-x c++ -Wno-ctor-dtor-privacy"/>
+		<set name="DATA_SEGMENT_START" value="$(SPLIT_OPTION) $(RW_BASE_OPTION)"/>
+		<set name="DEBUG_OPTIMISATION" value="-O0"/>
+		<set name="DEPEND_OPTION" value="-MD -MF"/>
+		<set name="ENUM_OPTION" value=""/>
+		<set name="EXCEPTIONS" value="-fexceptions"/>
+		<set name="EXPORT_VTBL_OPTION" value=""/>
+		<set name="EXTRA_CC_OPTION" value=""/>
+		<set name="EXTRA_LD_OPTION" value=""/>
+		<set name="FPMODE_OPTION" value=""/>
+		<set name="HEADER_FILES_CONTROL_OPTION" value=""/>
+		<set name="INSTRUCTION_SET" value=""/>
+		<set name="KERNEL_STATIC_RUNTIME_LIB" value="ksrt3_1.lib"/>
+		<set name="LD.ARMV5" value=""/>
+		<set name="LD.ARMV6" value=""/>
+		<set name="LD.ARMV7" value=""/>
+		<set name="LD_ERRORS_CONTROL_OPTION" value=""/>
+		<set name="LD_WARNINGS_CONTROL_OPTION" value="-Wl,--no-undefined"/>
+		<set name="LIBPATH" value=""/>
+		<set name="LIBRARY" value=""/>
+		<set name="LICENSERETRY_OPTION" value=""/>
+		<set name="LINKER_ADD_STATIC_RUNTIME" value="1"/>
+		<set name="LINKER_DEBUG_OPTION" value=""/>
+		<set name="LINKER_DEFAULT_LIB_PATHS" value=""/>
+		<set name="LINKER_DEFAULT_LIBS" value="-lsupc++ -lgcc"/>
+		<set name="LINKER_ENTRY_OPTION" value="-Wl,--entry"/>
+		<set name="LINKER_GROUP_END_OPTION" value="--end-group"/>
+		<set name="LINKER_GROUP_START_OPTION" value="--start-group"/>
+		<set name="LINKER_MISC_FLAGS" value="-Wl,$(CODE_SEGMENT_START),0x8000"/>
+		<set name="LINKER_NODEBUG_OPTION" value = "-Wl,--strip-debug"/>
+		<set name="LINKER_SCRIPT_FILE_OPTION" value="-T"/>
+		<set name="LINKER_SYMBOLS_FILE_OPTION" value="-Wl,-Map"/>
+		<set name="LINKER_SYMBOLS_OPTION" value=""/>
+		<set name="LISTING_OPTION" value="-S"/>
+		<set name="NEED_ENTRYPOINT_LIBRARY" value="" />
+		<set name="NEED_ENTRYPOINT_LIBRARY" value=""/>
+		<set name="NO_EXCEPTIONS" value="-fno-exceptions"/>
+		<set name="NO_UNALIGNED_ACCESS" value="$(CC.NO_UNALIGNED_ACCESS)"/>
+		<set name="OWN_LIBRARY_OPTION" value=""/>
+		<set name="PL.SOFTVFP_MAYBE_VFPV2" value="softvfp"/>
+		<set name="PL.SOFTVFP_MAYBE_VFPV3" value="softvfp"/>
+		<set name="PREINCLUDE" value="$(EPOCINCLUDE)/gcce/gcce.h"/>
+		<set name="PREINCLUDE_OPTION" value="-include"/>
+		<set name="PREPROCESSOR_OPTION" value="-E"/>
+		<set name="REL_OPTIMISATION" value="-O2"/>
+		<set name="RELOCATABLE_IMAGE_OPTION" value=""/>
+		<set name="RUNTIME_SYMBOL_VISIBILITY_OPTION" value=""/>
+		<set name="RVCTBIN" value="" />
+		<set name="RVCTINC" value="" />
+		<set name="RVCTLIB" value=""/>
+		<set name="RW_BASE" value="$(RW_BASE_OPTION)0x400000"/>
+		<set name="RW_BASE_OPTION" value="-Wl,-Tdata,"/>
+		<set name="SHARED_OBJECT_OPTION" value="-Wl,-shared"/>
+		<set name="SID" value=""/>
+		<set name="SO_NAME_OPTION" value="-Wl,-soname"/>
+		<set name="SPLIT_OPTION" value=""/>
+		<set name="STATIC_LIBS_LIST" value=""/>
+		<set name="STATIC_LIBS_PATH" value="" />
+		<set name="STDCPP_INCLUDE" value="$(EPOCINCLUDE)/stdapis"/>
+		<set name="STDLIB_OPTION" value="-nodefaultlibs"/>
+		<set name="SUPPORTS_ABIV1_IMPLIBS" value=""/>	
+		<set name="SYMBIAN_LD_MESSAGE_OPTION" value="$(LD_WARNINGS_CONTROL_OPTION) $(LD_ERRORS_CONTROL_OPTION)"/>
+		<set name="SYMVER_OPTION" value="-Wl,--default-symver"/>
+		<set name="TARGET_RELOCATION_OPTION" value="--target1-rel" />
+		<set name="TEMP_FILES_OPTION" value="-pipe"/>
+		<set name="THUMB_INSTRUCTION_SET" value="-mthumb"/>
+		<set name="TRANSFORM_CIA" value=""/>		
+		<set name="UNDEFINED_SYMBOL_REF_OPTION" value="-u"/>
+		<set name="UNRESOLVED_SYMBOL_REF_OPTION" value=""/>
+		<set name="USER_LIBS_PATH_OPTION" value="--userlibpath"/>
+		<set name="USER_STATIC_RUNTIME_LIB" value="usrt3_1.lib"/>
+		<set name="USER_STATIC_RUNTIME_LIB_NESTED_EXCEPTIONS" value="usrt_nx_3_1.lib"/>
+		<set name="USERINCLUDE" value=""/>
+		<set name="VFE_OPTION" value=""/>
+
+		<append name="CDEFS" value="__GCCE__"/>
+	</var>
+</build>
--- a/sbsv2/raptor/lib/config/gccxml.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/gccxml.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,115 +1,116 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- build configurations for the gccxml_cc1plus C++ language processor -->
-	<var name="gccxml_base" extends="root">
-		<varRef ref="default.interfaces"/>
-		<varRef ref="default.locations"/>
-		<!-- picked up from the Environment -->
-		<env name='CPP' default='$(GNUCPP)' type='tool'/>
-		<env name='BMCONV' default="$(EPOCROOT)/epoc32/tools/bmconv$(DOTEXE)" type='tool'/>
-		<env name='CREATERFIFILE' default='$(PERL) $(SBS_HOME)/bin/createrfifile.pl ' type='path'/>
-		<env name='GNUAWK' default='$(GNUPREFIX)gawk$(DOTEXE)' type='tool' versionCommand='$(GNUAWK) --version' versionResult='GNU Awk [3-9].*'/>
-		<env name='MAKEDEF' default='$(PERL) $(EPOCROOT)/epoc32/tools/makedef.pl' type='path'/>
-		<env name='PREPDEF' default='$(PERL) $(EPOCROOT)/epoc32/tools/prepdef.pl' type='path'/>
-		<env name='RCOMP' default='$(EPOCROOT)/epoc32/tools/rcomp$(DOTEXE)' type='tool'/>
-		<env name='RVCT22BIN' type='path'/>
-		<env name='RVCT22INC' type='path'/>
-		<env name='RVCT22LIB' type='path'/>
-		<env name='STRINGTABLE' default='$(PERL) $(EPOCROOT)/epoc32/tools/stringtable.pl' type='path'/>
-
-		<!-- link to bld.inf and mmp platform names -->
-		<set name='TRADITIONAL_PLATFORM' value='GCCXML'/>
-
-		<!-- interfaces -->
-		<set name="INTERFACE.ani" value="analysis.ani"/>
-		<set name="INTERFACE.dll" value="analysis.dll"/>
-		<set name="INTERFACE.exe" value="analysis.exe"/>
-		<set name="INTERFACE.exexp" value="analysis.exexp"/>
-		<set name="INTERFACE.extension" value="analysis.extension"/>
-		<set name="INTERFACE.implib" value="analysis.implib"/>
-		<set name="INTERFACE.fsy" value="analysis.fsy"/>
-		<set name="INTERFACE.kdll" value="analysis.kdll"/>
-		<set name="INTERFACE.kext" value="analysis.kext"/>
-		<set name="INTERFACE.klib" value="analysis.klib"/>
-		<set name="INTERFACE.ldd" value="analysis.ldd"/>
-		<set name="INTERFACE.lib" value="analysis.lib"/>
-		<set name="INTERFACE.pdd" value="analysis.pdd"/>
-		<set name="INTERFACE.pdl" value="analysis.pdl"/>
-		<set name="INTERFACE.plugin" value="analysis.plugin"/>
-		<set name="INTERFACE.resource" value="analysis.resource"/>
-		<set name="INTERFACE.stddll" value="analysis.stddll"/>
-		<set name="INTERFACE.stdexe" value="analysis.stdexe"/>
-		<set name="INTERFACE.stdlib" value="analysis.stdlib"/>
-		<set name="INTERFACE.textnotifier2" value="analysis.textnotifier2"/>
-		<set name="INTERFACE.var" value="analysis.var"/>
-		<set name="INTERFACE.var2" value="analysis.var2"/>
-		<!-- the following should really be done via the default "Symbian.*" interfaces from standard.xml - but they're currently tied to non-defaulted ARM build specifics -->
-		<set name="INTERFACE.none" value="analysis.none"/>
-
-		<!-- Java used by Trace Compiler -->
-		<env name='JAVA_HOME' default='' type='path'/>
-		<env name='JAVATC' default='$(JAVA_HOME)/bin/java' type='tool'/>
-
-		<!-- note that gccxml_cc1plus should be version checked, but I've yet to find a reliable way of doing this -->
-		<set name='CC' value="$(EPOCROOT)/epoc32/tools/gccxml_cc1plus$(DOTEXE)" type='tool'/>
-		<set name='CDEFS' value='_UNICODE __SYMBIAN32__ __GCC32__ __EPOC32__ __MARM__ __MINGW32__ _STLP_LITTLE_ENDIAN __GCCXML__ __MARM_ARM4__ $(MMPDEFS)'/>
-		<set name='CFLAGS' value='-bi -nostdinc -Wall -Wno-ctor-dtor-privacy -Wno-unknown-pragmas -UWIN32 -fshort-wchar -quiet -w '/>
-
-		<!-- in support of TEMs - processed as if in an RVCT build -->
-		<set name='RVCTBIN' value='$(RVCT22BIN)'/>
-		<set name='RVCTINC' value='$(RVCT22INC)'/>
-		<set name='RVCTLIB' value='$(RVCT22LIB)'/>
-
-		<set name='CPPFLAGS' value='-nostdinc -M -MG'/>
-
-		<set name='MMPDEFS' value=''/>
-		<set name='NMAKE' value='nmake$(DOTEXE)'/>
-		<set name='NMAKEFLAGS' value='-nologo -x - '/>
-		<set name='MAIN_OUTPUTPATH' value='$(EPOCROOT)/epoc32/build'/>
-		<set name='OUTPUTPATH' value='$(MAIN_OUTPUTPATH)'/>
-		<set name='RELEASEPATH' value='$(EPOCROOT)/epoc32/release'/>
-		<set name='SBSV1MAKE' value='$(EPOCROOT)/epoc32/tools/make$(DOTEXE)'/>
-		<set name='SYSTEMINCLUDE' value=''/>
-		<set name='TARGET' value='TARGET_WAS_NOT_SET_PROPERLY'/>
-		<set name='TARGETPATH' value=''/>
-		<set name='TARGETTYPE' value='TARGETTYPE_WAS_NOT_SET_PROPERLY'/>
-		<set name='USERINCLUDE' value=''/>
-		<set name='VARIANTPLATFORM' value='gccxml'/>
-
-		<set name='OPT.DEFINE' value='-D'/>
-		<set name='OPT.OUT' value='-o '/>
-		<set name='OPT.PREINCLUDE' value='-include '/>
-		<set name='OPT.SPLITINCLUDE' value=' -I- '/>
-		<set name='OPT.SYSINCLUDE' value='-I '/>
-		<set name='OPT.USERINCLUDE' value='-I '/>
-		<set name='PLATMACROS.WINDOWS' value='GCCXML ARMCC EPOC32 MARM EABI ARMCC_2 ARMCC_2_2 GENERIC_MARM MARM_ARMV5'/>
-		<set name='PLATMACROS.LINUX' value='$(PLATMACROS.WINDOWS)'/>
-		
-		<set name='KERNEL_MODE_DEF' value='__KERNEL_MODE__'/>
-		<set name='KERNEL_MODE_INCLUDES' value='$(EPOCINCLUDE)/nkern $(EPOCINCLUDE)/kernel/arm $(EPOCINCLUDE)/memmodel/epoc $(EPOCINCLUDE)/kernel $(EPOCINCLUDE)/nkern/arm'/>
-		<set name='STDCPP_DEF' value='__SYMBIAN_STDCPP_SUPPORT__'/>
-		<set name='STDCPP_INCLUDE' value='$(EPOCINCLUDE)/stdapis'/>
-	</var>
-
-	<var name="gccxml_udeb" extends="gccxml_base">
-		<set name='FULLVARIANTPATH' value='gccxml/udeb'/>
-		<set name='VARIANTTYPE' value='udeb'/>
-
-		<append name='CDEFS' value='_DEBUG'/>
-		<append name='CFLAGS' value='-g'/>
-	</var>
-
-	<var name="gccxml_urel" extends="gccxml_base">
-		<set name='FULLVARIANTPATH' value='gccxml/urel'/>
-		<set name='VARIANTTYPE' value='urel'/>
-
-		<append name='CDEFS' value='NDEBUG'/>
-		<append name='CFLAGS' value='-fomit-frame-pointer'/>
-	</var>
-
-	<group name="gccxml">
-		<varRef ref="gccxml_urel"/>
-		<varRef ref="gccxml_udeb"/>
-	</group>
-</build>
-
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- build variants for the gccxml_cc1plus C++ language processor -->
+	<var name="gccxml_base" extends="root">
+		<varRef ref="default.interfaces"/>
+		<varRef ref="default.locations"/>
+		
+		<!-- tools and scripts -->
+		<env name='BMCONV' default="$(EPOCROOT)/epoc32/tools/bmconv$(DOTEXE)" type='tool'/>
+		<set name='CC' value="$(EPOCROOT)/epoc32/tools/gccxml_cc1plus$(DOTEXE)" type='tool'/>
+		<env name='CPP' default='$(GNUCPP)' type='tool'/>
+		<env name='CREATERFIFILE' default='$(PERL) $(SBS_HOME)/bin/createrfifile.pl ' type='script'/>
+		<env name='GNUAWK' default='$(GNUPREFIX)gawk$(DOTEXE)' type='tool' versionCommand='$(GNUAWK) --version' versionResult='GNU Awk [3-9].*'/>
+		<env name='MAKEDEF' default='$(PERL) $(EPOCROOT)/epoc32/tools/makedef.pl' type='script'/>
+		<env name='PREPDEF' default='$(PERL) $(EPOCROOT)/epoc32/tools/prepdef.pl' type='script'/>
+		<env name='RCOMP' default='$(EPOCROOT)/epoc32/tools/rcomp$(DOTEXE)' type='tool'/>
+		<env name='STRINGTABLE' default='$(PERL) $(EPOCROOT)/epoc32/tools/stringtable.pl' type='script'/>
+
+		<!-- link to bld.inf and mmp platform names -->
+		<set name='TRADITIONAL_PLATFORM' value='GCCXML'/>
+
+		<!-- interfaces -->
+		<set name="INTERFACE.ani" value="analysis.ani"/>
+		<set name="INTERFACE.dll" value="analysis.dll"/>
+		<set name="INTERFACE.exe" value="analysis.exe"/>
+		<set name="INTERFACE.exexp" value="analysis.exexp"/>
+		<set name="INTERFACE.extension" value="analysis.extension"/>
+		<set name="INTERFACE.implib" value="analysis.implib"/>
+		<set name="INTERFACE.fsy" value="analysis.fsy"/>
+		<set name="INTERFACE.kdll" value="analysis.kdll"/>
+		<set name="INTERFACE.kext" value="analysis.kext"/>
+		<set name="INTERFACE.klib" value="analysis.klib"/>
+		<set name="INTERFACE.ldd" value="analysis.ldd"/>
+		<set name="INTERFACE.lib" value="analysis.lib"/>
+		<set name="INTERFACE.pdd" value="analysis.pdd"/>
+		<set name="INTERFACE.pdl" value="analysis.pdl"/>
+		<set name="INTERFACE.plugin" value="analysis.plugin"/>
+		<set name="INTERFACE.resource" value="analysis.resource"/>
+		<set name="INTERFACE.stddll" value="analysis.stddll"/>
+		<set name="INTERFACE.stdexe" value="analysis.stdexe"/>
+		<set name="INTERFACE.stdlib" value="analysis.stdlib"/>
+		<set name="INTERFACE.textnotifier2" value="analysis.textnotifier2"/>
+		<set name="INTERFACE.var" value="analysis.var"/>
+		<set name="INTERFACE.var2" value="analysis.var2"/>
+		<!-- the following should really be done via the default "Symbian.*" interfaces from standard.xml - but they're currently tied to non-defaulted ARM build specifics -->
+		<set name="INTERFACE.none" value="analysis.none"/>
+
+		<!-- Java used by Trace Compiler -->
+		<env name='JAVA_HOME' default='' type='path'/>
+		<env name='JAVATC' default='$(JAVA_HOME)/bin/java' type='tool'/>
+
+		<!-- note that gccxml_cc1plus should be version checked, but I've yet to find a reliable way of doing this -->
+		<set name='CDEFS' value='_UNICODE __SYMBIAN32__ __GCC32__ __EPOC32__ __MARM__ __MINGW32__ _STLP_LITTLE_ENDIAN __GCCXML__ __MARM_ARM4__ $(MMPDEFS)'/>
+		<set name='CFLAGS' value='-bi -nostdinc -Wall -Wno-ctor-dtor-privacy -Wno-unknown-pragmas -UWIN32 -fshort-wchar -quiet -w '/>
+
+		<!-- in support of TEMs - processed as if in an RVCT build -->
+		<env name='RVCT22BIN' type='toolchainpath'/>
+		<env name='RVCT22INC' type='toolchainpath'/>
+		<env name='RVCT22LIB' type='toolchainpath'/>
+		<set name='RVCTBIN' value='$(RVCT22BIN)'/>
+		<set name='RVCTINC' value='$(RVCT22INC)'/>
+		<set name='RVCTLIB' value='$(RVCT22LIB)'/>
+
+		<set name='CPPFLAGS' value='-nostdinc -M -MG'/>
+
+		<set name='MMPDEFS' value=''/>
+		<set name='NMAKE' value='nmake$(DOTEXE)'/>
+		<set name='NMAKEFLAGS' value='-nologo -x - '/>
+		<set name='MAIN_OUTPUTPATH' value='$(EPOCROOT)/epoc32/build'/>
+		<set name='OUTPUTPATH' value='$(MAIN_OUTPUTPATH)'/>
+		<set name='RELEASEPATH' value='$(EPOCROOT)/epoc32/release'/>
+		<set name='SBSV1MAKE' value='$(EPOCROOT)/epoc32/tools/make$(DOTEXE)'/>
+		<set name='SYSTEMINCLUDE' value=''/>
+		<set name='TARGET' value='TARGET_WAS_NOT_SET_PROPERLY'/>
+		<set name='TARGETPATH' value=''/>
+		<set name='TARGETTYPE' value='TARGETTYPE_WAS_NOT_SET_PROPERLY'/>
+		<set name='USERINCLUDE' value=''/>
+		<set name='VARIANTPLATFORM' value='gccxml'/>
+
+		<set name='OPT.DEFINE' value='-D'/>
+		<set name='OPT.OUT' value='-o '/>
+		<set name='OPT.PREINCLUDE' value='-include '/>
+		<set name='OPT.SPLITINCLUDE' value=' -I- '/>
+		<set name='OPT.SYSINCLUDE' value='-I '/>
+		<set name='OPT.USERINCLUDE' value='-I '/>
+		<set name='PLATMACROS.WINDOWS' value='GCCXML ARMCC EPOC32 MARM EABI ARMCC_2 ARMCC_2_2 GENERIC_MARM MARM_ARMV5'/>
+		<set name='PLATMACROS.LINUX' value='$(PLATMACROS.WINDOWS)'/>
+		
+		<set name='KERNEL_MODE_DEF' value='__KERNEL_MODE__'/>
+		<set name='KERNEL_MODE_INCLUDES' value='$(EPOCINCLUDE)/nkern $(EPOCINCLUDE)/kernel/arm $(EPOCINCLUDE)/memmodel/epoc $(EPOCINCLUDE)/kernel $(EPOCINCLUDE)/nkern/arm'/>
+		<set name='STDCPP_DEF' value='__SYMBIAN_STDCPP_SUPPORT__'/>
+		<set name='STDCPP_INCLUDE' value='$(EPOCINCLUDE)/stdapis'/>
+	</var>
+
+	<var name="gccxml_udeb" extends="gccxml_base">
+		<set name='FULLVARIANTPATH' value='gccxml/udeb'/>
+		<set name='VARIANTTYPE' value='udeb'/>
+
+		<append name='CDEFS' value='_DEBUG'/>
+		<append name='CFLAGS' value='-g'/>
+	</var>
+
+	<var name="gccxml_urel" extends="gccxml_base">
+		<set name='FULLVARIANTPATH' value='gccxml/urel'/>
+		<set name='VARIANTTYPE' value='urel'/>
+
+		<append name='CDEFS' value='NDEBUG'/>
+		<append name='CFLAGS' value='-fomit-frame-pointer'/>
+	</var>
+
+	<group name="gccxml">
+		<varRef ref="gccxml_urel"/>
+		<varRef ref="gccxml_udeb"/>
+	</group>
+</build>
+
--- a/sbsv2/raptor/lib/config/interfaces.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/interfaces.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,42 +1,44 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- The standard interfaces used by most configurations. -->
-
-	<var name="default.interfaces">
-		<!-- interfaces corresponding to target types -->
-
-		<set name="INTERFACE_TYPES" value="exe stdexe ext_makefile dll stddll lib stdlib export extension ani plugin textnotifier2 implib var var2 exexp kexe kdll kext klib ldd pdd pdl fsy resource none stringtable bitmap"/>
-		<set name="INTERFACE.exe" value="Symbian.exe"/>
-		<set name="INTERFACE.stdexe" value="Symbian.stdexe"/>
-		<set name="INTERFACE.stddll" value="Symbian.stddll"/>
-		<set name="INTERFACE.stdlib" value="Symbian.stdlib"/>
-		<set name="INTERFACE.dll" value="Symbian.dll"/>
-		<set name="INTERFACE.lib" value="Symbian.lib"/>
-		<set name="INTERFACE.ani" value="Symbian.ani"/>
-		<set name="INTERFACE.plugin" value="Symbian.plugin"/>
-		<set name="INTERFACE.textnotifier2" value="Symbian.textnotifier2"/>
-		<set name="INTERFACE.implib" value="Symbian.implib"/>
-		<set name="INTERFACE.var" value="Symbian.var"/>
-		<set name="INTERFACE.var2" value="Symbian.var2"/>
-		<set name="INTERFACE.exexp" value="Symbian.exexp"/>
-		<set name="INTERFACE.kexe" value="Symbian.kexe"/>
-		<set name="INTERFACE.kdll" value="Symbian.kdll"/>
-		<set name="INTERFACE.kext" value="Symbian.kext"/>
-		<set name="INTERFACE.klib" value="Symbian.klib"/>
-		<set name="INTERFACE.ldd" value="Symbian.ldd"/>
-		<set name="INTERFACE.pdd" value="Symbian.pdd"/>
-		<set name="INTERFACE.pdl" value="Symbian.pdl"/>
-		<set name="INTERFACE.fsy" value="Symbian.fsy"/>
-		<set name="INTERFACE.none" value="Symbian.none"/>
-		<set name="INTERFACE.ext_makefile" value="base.ext_makefile"/>
-		<set name="INTERFACE.extension" value="base.extension"/>
-		<set name="INTERFACE.export" value="base.export"/>
-		<set name="INTERFACE.resource" value="base.resource"/>
-		<set name="INTERFACE.stringtable" value="base.stringtable"/>
-		<set name="INTERFACE.bitmap" value="base.bitmap"/>
-
-		<!-- per-configuration default interfaces -->
-		<set name="INTERFACE.config" value="Symbian.config.default"/>
-	</var>
-
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- The standard interfaces used by most configurations. -->
+
+	<var name="default.interfaces">
+		<!-- interfaces corresponding to target types -->
+
+		<set name="INTERFACE_TYPES" value="exe stdexe ext_makefile dll stddll lib stdlib export extension ani plugin plugin3 textnotifier2 implib var var2 exexp kexe kdll kext klib pdll ldd pdd pdl fsy resource none stringtable bitmap"/>
+		<set name="INTERFACE.exe" value="Symbian.exe"/>
+		<set name="INTERFACE.stdexe" value="Symbian.stdexe"/>
+		<set name="INTERFACE.stddll" value="Symbian.stddll"/>
+		<set name="INTERFACE.stdlib" value="Symbian.stdlib"/>
+		<set name="INTERFACE.dll" value="Symbian.dll"/>
+		<set name="INTERFACE.pdll" value="Symbian.pdll"/>
+		<set name="INTERFACE.lib" value="Symbian.lib"/>
+		<set name="INTERFACE.ani" value="Symbian.ani"/>
+		<set name="INTERFACE.plugin" value="Symbian.plugin"/>
+		<set name="INTERFACE.plugin3" value="Symbian.plugin3"/>
+		<set name="INTERFACE.textnotifier2" value="Symbian.textnotifier2"/>
+		<set name="INTERFACE.implib" value="Symbian.implib"/>
+		<set name="INTERFACE.var" value="Symbian.var"/>
+		<set name="INTERFACE.var2" value="Symbian.var2"/>
+		<set name="INTERFACE.exexp" value="Symbian.exexp"/>
+		<set name="INTERFACE.kexe" value="Symbian.kexe"/>
+		<set name="INTERFACE.kdll" value="Symbian.kdll"/>
+		<set name="INTERFACE.kext" value="Symbian.kext"/>
+		<set name="INTERFACE.klib" value="Symbian.klib"/>
+		<set name="INTERFACE.ldd" value="Symbian.ldd"/>
+		<set name="INTERFACE.pdd" value="Symbian.pdd"/>
+		<set name="INTERFACE.pdl" value="Symbian.pdl"/>
+		<set name="INTERFACE.fsy" value="Symbian.fsy"/>
+		<set name="INTERFACE.none" value="Symbian.none"/>
+		<set name="INTERFACE.ext_makefile" value="base.ext_makefile"/>
+		<set name="INTERFACE.extension" value="base.extension"/>
+		<set name="INTERFACE.export" value="base.export"/>
+		<set name="INTERFACE.resource" value="base.resource"/>
+		<set name="INTERFACE.stringtable" value="base.stringtable"/>
+		<set name="INTERFACE.bitmap" value="base.bitmap"/>
+
+		<!-- per-configuration default interfaces -->
+		<set name="INTERFACE.config" value="Symbian.config.default"/>
+	</var>
+
+</build>
--- a/sbsv2/raptor/lib/config/locations.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/locations.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,116 +1,118 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- The standard locations for widely used tools and resources.
-
-       This is easier to maintain than defining the locations in each
-       configuration that uses a tool or resource.
-	-->
-
-	<var name="hostplatform.locations" host='linux.*'>	
-		<set name='DOTEXE' value=''/>
-		<set name='GCCPREFIX' value='/usr/bin/'/>
-		<set name='GNUPREFIX' value='/bin/'/>
-		
-		<env name='HOSTPLATFORM_DIR' default='linux-i386' />
-		<env name='HOSTPLATFORM' default='linux i386'/>
-		
-		<env name='SBS_GNUCPP' default='/usr/bin/cpp' type='tool'/>
-		<env name='SBS_GNUDATE' default='/bin/date' type='tool'/>
-		<env name='SBS_GNUMAKE38' default='$(SBS_HOME)/$(HOSTPLATFORM_DIR)/bin/make' type='tool'/>
-		<env name='SBS_GNUSED' default='/bin/sed' type='tool'/>
-		<env name='SBS_GNUMKDIR' default='/bin/mkdir' type='tool'/>
-		<env name='SBS_GNUMV' default='/bin/mv' type='tool'/>
-		<env name='SBS_GNUCP' default='/bin/cp' type='tool'/>
-		<env name='SBS_GNUCAT' default='/bin/cat' type='tool'/>
-		<env name='SBS_GNURM' default='/bin/rm' type='tool'/>
-		<env name='SBS_GNULN' default='/bin/ln' type='tool'/>
-		<env name='SBS_GNURMDIR' default='/bin/rmdir' type='tool'/>
-		<env name='SBS_GNUCHMOD' default='/bin/chmod' type='tool'/>
-		<env name='SBS_GNUMD5SUM' default='/usr/bin/md5sum' type='tool'/>
-		<env name='SBS_GNUTOUCH' default='/bin/touch' type='tool'/>
-		<env name='SBS_GNUFIND' default='/usr/bin/find' type='tool'/>
-		<env name='SBS_GNUGREP' default='/bin/grep' type='tool'/>
-		<env name='SBS_GNUSORT' default='/bin/sort' type='tool'/>
-		<env name='SBS_SHELL' default="$(SBS_HOME)/$(HOSTPLATFORM_DIR)/bin/sh" type='tool'/>
-		<env name='SBS_ZIP' default="$(SBS_HOME)/$(HOSTPLATFORM_DIR)/bin/zip" type='tool'/>
-		<env name='SBS_UNZIP' default="$(SBS_HOME)/$(HOSTPLATFORM_DIR)/bin/unzip" type='tool'/>
-		<env name='SBS_BVCPP' default="$(SBS_HOME)/$(HOSTPLATFORM_DIR)/bv/bin/cpp" type='tool'/>
-		<env name='SBS_PERL' default='perl' type='tool'/>
-		<env name='SBS_PYTHON' default='python' type='tool'/>
-	</var>
-	<var name="hostplatform.locations" host='win.*' >
-		<set name='COREUTILSBINDIR' value='$(SBS_CYGWIN)/bin' type='path'/>
-		<set name='DOTEXE' value='.exe'/>
-		<set name='GNUPREFIX' value='$(COREUTILSBINDIR)/'/>
-		<set name='GCCPREFIX' value='$(MINGWBINDIR)/'/>
-		<set name='MINGWBINDIR' value='$(SBS_MINGW)/bin' type='path'/>
-		
-		<env name='HOSTPLATFORM_DIR' default='win32' /> 
-		<env name='HOSTPLATFORM' default='win 32' />
-		
-		<env name='SBS_CYGWIN' default='$(SBS_HOME)/$(HOSTPLATFORM_DIR)/cygwin' type='path'/>
-		<env name='SBS_MINGW' default='$(SBS_HOME)/$(HOSTPLATFORM_DIR)/mingw' type='path'/>
-		<env name='SBS_GNUCPP' default='$(MINGWBINDIR)/cpp.exe' type='tool'/>
-		<env name='SBS_GNUDATE' default='$(COREUTILSBINDIR)/date.exe' type='tool'/>
-		<env name='SBS_GNUMAKE38' default='$(MINGWBINDIR)/make.exe' type='tool'/>
-		<env name='SBS_GNUSED' default='$(COREUTILSBINDIR)/sed.exe' type='tool'/>
-		<env name='SBS_GNUMKDIR' default='$(COREUTILSBINDIR)/mkdir.exe' type='tool'/>
-		<env name='SBS_GNUCP' default='$(COREUTILSBINDIR)/cp.exe' type='tool'/>
-		<env name='SBS_GNUMV' default='$(COREUTILSBINDIR)/mv.exe' type='tool'/>
-		<env name='SBS_GNUCAT' default='$(COREUTILSBINDIR)/cat.exe' type='tool'/>
-		<env name='SBS_GNURM' default='$(COREUTILSBINDIR)/rm.exe' type='tool'/>
-		<env name='SBS_GNULN' default='$(COREUTILSBINDIR)/ln.exe' type='tool'/>
-		<env name='SBS_GNURMDIR' default='$(COREUTILSBINDIR)/rmdir.exe' type='tool'/>
-		<env name='SBS_GNUCHMOD' default='$(COREUTILSBINDIR)/chmod.exe' type='tool'/>
-		<env name='SBS_GNUMD5SUM' default='$(COREUTILSBINDIR)/md5sum.exe' type='tool'/>
-		<env name='SBS_GNUTOUCH' default='$(COREUTILSBINDIR)/touch.exe' type='tool'/>
-		<env name='SBS_GNUFIND' default='$(COREUTILSBINDIR)/find.exe' type='tool'/>
-		<env name='SBS_GNUGREP' default='$(COREUTILSBINDIR)/grep.exe' type='tool'/>
-		<env name='SBS_GNUSORT' default='$(COREUTILSBINDIR)/sort.exe' type='tool'/>
-		<env name='SBS_SHELL' default="$(COREUTILSBINDIR)/sh.exe" type='tool'/>
-		<env name='SBS_ZIP' default="$(COREUTILSBINDIR)/zip.exe" type='tool'/>
-		<env name='SBS_UNZIP' default="$(COREUTILSBINDIR)/unzip.exe" type='tool'/>
-		<env name='SBS_BVCPP' default="$(SBS_HOME)/$(HOSTPLATFORM_DIR)/bv/bin/cpp.exe" type='tool'/>
-		<env name='SBS_PERL' default='perl.exe' type='tool'/>
-		<env name='SBS_PYTHON' default='$(SBS_HOME)/$(HOSTPLATFORM_DIR)/python252/python.exe' type='tool'/>
-	</var>
-
-	<var name="default.locations" extends="hostplatform.locations">
-		<env name='EPOCROOT' default='' type='path'/>
-		<!-- Place where intermediate files are built -->
-		<env name='SBS_BUILD_DIR' default='$(EPOCROOT)/epoc32/build' type='path'/>
-
-		<set name='DATE' value='$(SBS_GNUDATE)' type='tool'/>
-		<set name='GNUCPP' value='$(SBS_GNUCPP)' type='tool' versionCommand='$(GNUCPP) --version' versionResult='cpp(.exe)? .* [345]\..*'/>
-		<set name='GNUCP' value='$(SBS_GNUCP)' type='tool' versionCommand='$(GNUCP) --version' versionResult='cp(.exe)?\s*\((GNU\s*)?coreutils\)\s*[5-9]\..*'/>
-		<set name='GNUMV' value='$(SBS_GNUMV)' type='tool' versionCommand='$(GNUMV) --version' versionResult='mv(.exe)?\s*\((GNU\s*)?coreutils\)\s*[5-9]\..*'/>
-		<set name='GNUCAT' value='$(SBS_GNUCAT)' type='tool' versionCommand='$(GNUCAT) --version' versionResult='cat(.exe)?\s*\((GNU\s*)?coreutils\)\s*[5-9]\..*'/>
-		<set name='GNUMAKE38' value='$(SBS_GNUMAKE38)' type='tool' versionCommand='$(GNUMAKE38) -v' versionResult='GNU Make 3.8[1-9]'/>
-		<set name='GNUSED' value='$(SBS_GNUSED)' type='tool' versionCommand='$(GNUSED) --version' versionResult='GNU sed version [3-9].*'/>
-		<set name='GNUMKDIR' value='$(SBS_GNUMKDIR)' type='tool' versionCommand='$(GNUMKDIR) --version' versionResult='.*'/>
-		<set name='GNURM' value='$(SBS_GNURM)' type='tool' versionCommand='$(GNURM) --version' versionResult='rm.*coreutils.*'/>
-		<set name='GNULN' value='$(SBS_GNULN)' type='tool' versionCommand='$(GNULN) --version' versionResult='ln.*coreutils.*'/>
-		<set name='GNURMDIR' value='$(SBS_GNURMDIR)' type='tool' versionCommand='$(GNURMDIR) --version' versionResult='rmdir.*coreutils.*'/>
-		<set name='GNUCHMOD' value='$(SBS_GNUCHMOD)' type='tool' versionCommand='$(GNUCHMOD) --version' versionResult='chmod.*coreutils.*'/>
-		<set name='GNUMD5SUM' value='$(SBS_GNUMD5SUM)' type='tool' versionCommand='$(GNUMD5SUM) --version' versionResult='md5sum.*coreutils.*'/>
-		<set name='GNUTOUCH' value='$(SBS_GNUTOUCH)' type='tool' versionCommand='$(GNUTOUCH) --version' versionResult='touch.*coreutils.*'/>
-		<set name='GNUFIND' value='$(SBS_GNUFIND)' type='tool' versionCommand='$(GNUFIND) --version' versionResult='(GNU)?.*find.*(GNU)?.*'/>
-		<set name='GNUGREP' value='$(SBS_GNUGREP)' type='tool' versionCommand='$(GNUGREP) --version' versionResult='(GNU)?.*grep.*(GNU)?.*'/>
-		<set name='GNUSORT' value='$(SBS_GNUSORT)' type='tool' versionCommand='$(GNUSORT) --version' versionResult='(GNU)?.*sort.*(GNU)?.*'/>
-		<set name='ZIP' value="$(SBS_ZIP)" type='tool'/>
-		<set name='UNZIP' value="$(SBS_UNZIP)" type='tool'/>
-		<set name='PERL' value='$(SBS_PERL)' type='tool'/>
-		<set name='PYTHON' value='$(SBS_PYTHON)' type='tool' versionCommand='$(PYTHON) -V' versionResult='Python 2\.[456].*'/>
-
-		<set name='DEFAULT_PLATFORMS' value='ARMV5 ARMV7 WINSCW'/>
-		<set name='BASE_DEFAULT_PLATFORMS' value='ARMV5 ARMV7 WINSCW ARMV5SMP'/>
-		<set name='BASE_USER_DEFAULT_PLATFORMS' value='ARMV5 ARMV7 WINSCW'/>
-
-		<set name='BUILD_INCLUDE' value=''/>
-		<set name='CREATEVMAP' value='$(PYTHON) $(SBS_HOME)/bin/createvmap.py' type='tool'/>
-		<set name='CREATEVMAPCPP' value='$(SBS_BVCPP)' type='tool'/>
-		<set name='FEATURELISTFILES' value=''/>
-		<set name='FEATUREVARIANTNAME' value=''/>
-	</var>
-
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- The standard locations for widely used tools and resources.
+
+       This is easier to maintain than defining the locations in each
+       configuration that uses a tool or resource.
+	-->
+
+	<var name="hostplatform.locations" host='linux.*'>	
+		<set name='DOTEXE' value=''/>
+		<set name='GCCPREFIX' value='/usr/bin/'/>
+		<set name='GNUPREFIX' value='/bin/'/>
+		
+		<env name='HOSTPLATFORM_DIR' default='linux-i386' />
+		<env name='HOSTPLATFORM' default='linux i386'/>
+		
+		<env name='SBS_GNUCPP' default='/usr/bin/cpp' type='tool'/>
+		<env name='SBS_GNUDATE' default='/bin/date' type='tool'/>
+		<env name='SBS_GNUMAKE38' default='$(SBS_HOME)/$(HOSTPLATFORM_DIR)/bin/make' type='tool'/>
+		<env name='SBS_GNUSED' default='/bin/sed' type='tool'/>
+		<env name='SBS_GNUMKDIR' default='/bin/mkdir' type='tool'/>
+		<env name='SBS_GNUMV' default='/bin/mv' type='tool'/>
+		<env name='SBS_GNUCP' default='/bin/cp' type='tool'/>
+		<env name='SBS_GNUCAT' default='/bin/cat' type='tool'/>
+		<env name='SBS_GNURM' default='/bin/rm' type='tool'/>
+		<env name='SBS_GNULN' default='/bin/ln' type='tool'/>
+		<env name='SBS_GNURMDIR' default='/bin/rmdir' type='tool'/>
+		<env name='SBS_GNUCHMOD' default='/bin/chmod' type='tool'/>
+		<env name='SBS_GNUMD5SUM' default='/usr/bin/md5sum' type='tool'/>
+		<env name='SBS_GNUTOUCH' default='/bin/touch' type='tool'/>
+		<env name='SBS_GNUFIND' default='/usr/bin/find' type='tool'/>
+		<env name='SBS_GNUGREP' default='/bin/grep' type='tool'/>
+		<env name='SBS_GNUSORT' default='sort' type='tool'/>
+		<env name='SBS_SHELL' default="$(SBS_HOME)/$(HOSTPLATFORM_DIR)/bin/sh" type='tool'/>
+		<env name='SBS_ZIP' default="$(SBS_HOME)/$(HOSTPLATFORM_DIR)/bin/zip" type='tool'/>
+		<env name='SBS_UNZIP' default="$(SBS_HOME)/$(HOSTPLATFORM_DIR)/bin/unzip" type='tool'/>
+		<env name='SBS_BVCPP' default="$(SBS_HOME)/$(HOSTPLATFORM_DIR)/bv/bin/cpp" type='tool'/>
+		<env name='SBS_PERL' default='perl' type='tool'/>
+		<env name='SBS_PYTHON' default='python' type='tool'/>
+	</var>
+	<var name="hostplatform.locations" host='win.*' >
+		<set name='COREUTILSBINDIR' value='$(SBS_CYGWIN)/bin' type='path'/>
+		<set name='DOTEXE' value='.exe'/>
+		<set name='GNUPREFIX' value='$(COREUTILSBINDIR)/'/>
+		<set name='GCCPREFIX' value='$(MINGWBINDIR)/'/>
+		<set name='MINGWBINDIR' value='$(SBS_MINGW)/bin' type='path'/>
+		
+		<env name='HOSTPLATFORM_DIR' default='win32' /> 
+		<env name='HOSTPLATFORM' default='win 32' />
+		
+		<env name='SBS_CYGWIN' default='$(SBS_HOME)/$(HOSTPLATFORM_DIR)/cygwin' type='path'/>
+		<env name='SBS_MINGW' default='$(SBS_HOME)/$(HOSTPLATFORM_DIR)/mingw' type='path'/>
+		<env name='SBS_GNUCPP' default='$(MINGWBINDIR)/cpp.exe' type='tool'/>
+		<env name='SBS_GNUDATE' default='$(COREUTILSBINDIR)/date.exe' type='tool'/>
+		<env name='SBS_GNUMAKE38' default='$(MINGWBINDIR)/make.exe' type='tool'/>
+		<env name='SBS_GNUSED' default='$(COREUTILSBINDIR)/sed.exe' type='tool'/>
+		<env name='SBS_GNUMKDIR' default='$(COREUTILSBINDIR)/mkdir.exe' type='tool'/>
+		<env name='SBS_GNUCP' default='$(COREUTILSBINDIR)/cp.exe' type='tool'/>
+		<env name='SBS_GNUMV' default='$(COREUTILSBINDIR)/mv.exe' type='tool'/>
+		<env name='SBS_GNUCAT' default='$(COREUTILSBINDIR)/cat.exe' type='tool'/>
+		<env name='SBS_GNURM' default='$(COREUTILSBINDIR)/rm.exe' type='tool'/>
+		<env name='SBS_GNULN' default='$(COREUTILSBINDIR)/ln.exe' type='tool'/>
+		<env name='SBS_GNURMDIR' default='$(COREUTILSBINDIR)/rmdir.exe' type='tool'/>
+		<env name='SBS_GNUCHMOD' default='$(COREUTILSBINDIR)/chmod.exe' type='tool'/>
+		<env name='SBS_GNUMD5SUM' default='$(COREUTILSBINDIR)/md5sum.exe' type='tool'/>
+		<env name='SBS_GNUTOUCH' default='$(COREUTILSBINDIR)/touch.exe' type='tool'/>
+		<env name='SBS_GNUFIND' default='$(COREUTILSBINDIR)/find.exe' type='tool'/>
+		<env name='SBS_GNUGREP' default='$(COREUTILSBINDIR)/grep.exe' type='tool'/>
+		<env name='SBS_GNUSORT' default='$(COREUTILSBINDIR)/sort.exe' type='tool'/>
+		<env name='SBS_SHELL' default="$(COREUTILSBINDIR)/sh.exe" type='tool'/>
+		<env name='SBS_ZIP' default="$(COREUTILSBINDIR)/zip.exe" type='tool'/>
+		<env name='SBS_UNZIP' default="$(COREUTILSBINDIR)/unzip.exe" type='tool'/>
+		<env name='SBS_BVCPP' default="$(SBS_HOME)/$(HOSTPLATFORM_DIR)/bv/bin/cpp.exe" type='tool'/>
+		<env name='SBS_PERL' default='perl.exe' type='tool'/>
+		<env name='SBS_PYTHON' default='python.exe' type='tool'/>
+	</var>
+
+	<var name="default.locations" extends="hostplatform.locations">
+		<env name='EPOCROOT' default='' type='path'/>
+		<env name='SBS_HOME' default='' type='path'/>
+		<!-- Place where intermediate files are built -->
+		<env name='SBS_BUILD_DIR' default='$(EPOCROOT)/epoc32/build' type='path'/>
+
+		<set name='DATE' value='$(SBS_GNUDATE)' type='tool'/>
+		<set name='GNUCPP' value='$(SBS_GNUCPP)' type='tool' versionCommand='$(GNUCPP) --version' versionResult='cpp(.exe)? .* [345]\..*'/>
+		<set name='GNUCP' value='$(SBS_GNUCP)' type='tool' versionCommand='$(GNUCP) --version' versionResult='cp(.exe)?\s*\((GNU\s*)?coreutils\)\s*[5-9]\..*'/>
+		<set name='GNUMV' value='$(SBS_GNUMV)' type='tool' versionCommand='$(GNUMV) --version' versionResult='mv(.exe)?\s*\((GNU\s*)?coreutils\)\s*[5-9]\..*'/>
+		<set name='GNUCAT' value='$(SBS_GNUCAT)' type='tool' versionCommand='$(GNUCAT) --version' versionResult='cat(.exe)?\s*\((GNU\s*)?coreutils\)\s*[5-9]\..*'/>
+		<set name='GNUMAKE38' value='$(SBS_GNUMAKE38)' type='tool' versionCommand='$(GNUMAKE38) -v' versionResult='GNU Make 3.8[1-9]'/>
+		<set name='GNUSED' value='$(SBS_GNUSED)' type='tool' versionCommand='$(GNUSED) --version' versionResult='GNU sed version [3-9].*'/>
+		<set name='GNUMKDIR' value='$(SBS_GNUMKDIR)' type='tool' versionCommand='$(GNUMKDIR) --version' versionResult='.*'/>
+		<set name='GNURM' value='$(SBS_GNURM)' type='tool' versionCommand='$(GNURM) --version' versionResult='rm.*coreutils.*'/>
+		<set name='GNULN' value='$(SBS_GNULN)' type='tool' versionCommand='$(GNULN) --version' versionResult='ln.*coreutils.*'/>
+		<set name='GNURMDIR' value='$(SBS_GNURMDIR)' type='tool' versionCommand='$(GNURMDIR) --version' versionResult='rmdir.*coreutils.*'/>
+		<set name='GNUCHMOD' value='$(SBS_GNUCHMOD)' type='tool' versionCommand='$(GNUCHMOD) --version' versionResult='chmod.*coreutils.*'/>
+		<set name='GNUMD5SUM' value='$(SBS_GNUMD5SUM)' type='tool' versionCommand='$(GNUMD5SUM) --version' versionResult='md5sum.*coreutils.*'/>
+		<set name='GNUTOUCH' value='$(SBS_GNUTOUCH)' type='tool' versionCommand='$(GNUTOUCH) --version' versionResult='touch.*coreutils.*'/>
+		<set name='GNUFIND' value='$(SBS_GNUFIND)' type='tool' versionCommand='$(GNUFIND) --version' versionResult='(GNU)?.*find.*(GNU)?.*'/>
+		<set name='GNUGREP' value='$(SBS_GNUGREP)' type='tool' versionCommand='$(GNUGREP) --version' versionResult='(GNU)?.*grep.*(GNU)?.*'/>
+		<set name='GNUSORT' value='$(SBS_GNUSORT)' type='tool' versionCommand='$(GNUSORT) --version' versionResult='(GNU)?.*sort.*(GNU)?.*'/>
+		<set name='ZIP' value="$(SBS_ZIP)" type='tool'/>
+		<set name='UNZIP' value="$(SBS_UNZIP)" type='tool'/>
+		<set name='PERL' value='$(SBS_PERL)' type='tool'/>
+		<set name='PYTHON' value='$(SBS_PYTHON)' type='tool' versionCommand='$(PYTHON) -V' versionResult='Python 2\.[456].*'/>
+		
+		<set name='DEFAULT_PLATFORMS' value='ARMV5 ARMV7 WINSCW'/>
+		<set name='BASE_DEFAULT_PLATFORMS' value='ARMV5 ARMV7 WINSCW ARMV5SMP'/>
+		<set name='BASE_USER_DEFAULT_PLATFORMS' value='ARMV5 ARMV7 WINSCW'/>
+
+		<set name='BUILD_INCLUDE' value=''/>
+		<set name='CREATEVMAP' value='$(PYTHON) $(SBS_HOME)/bin/createvmap.py' type='script'/>
+		<set name='DEPCRUNCH' value='$(PYTHON) $(SBS_HOME)/bin/depcrunch.py' type='script'/>
+		<set name='CREATEVMAPCPP' value='$(SBS_BVCPP)' type='tool'/>
+		<set name='FEATURELISTFILES' value=''/>
+		<set name='FEATUREVARIANTNAME' value=''/>
+	</var>
+
+</build>
--- a/sbsv2/raptor/lib/config/make.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/make.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,92 +1,103 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- Some common Raptor make engines -->
-	
-	<!-- Raptor make engine for GNU make -->
-	<var name="make_engine">
-		<varRef ref="default.locations"/>
-
-		<!-- Shell settings -->
-		<set name='DEFAULT_SHELL' value='$(SBS_HOME)/$(HOSTPLATFORM_DIR)/bin/talon$(DOTEXE)' type='tool'/>
-		<set name='TALON_SHELL' value='$(SBS_SHELL)' type='tool'/>
-		<set name='USE_TALON' value='1'/>
-		<set name='TALON_TIMEOUT' value='600000'/>
-		<set name='TALON_DESCRAMBLE' value='1'/>
-		
-		<!-- Command-line for initialisation -->
-		<set name="initialise" value=""/>
-
-		<!-- Command-line for shutdown -->
-		<set name="shutdown" value=""/>
-
-		<!-- Command-line for build  -->
-		<set name="build" value="$(GNUMAKE38) HAVE_ORDERONLY=1 -r" type="tool"/>
-
-		<!-- Options  -->
-		<set name="makefile" value="-f"/>
-		<set name="keep_going" value="-k"/>
-		<set name="jobs" value="-j"/>
-		
-		<!-- The following are stuck on the commandline before any options
-		     specified by the sbs "mo" option, so they can be overridden -->
-		<set name="defaultoptions" value=""/>
-
-		<!-- How to split out the makefiles -->
-		<set name="selectors" value="export,bitmap,resource_deps,resource,default"/>
-		<set name="export.selector.iface" value="\.export$"/>
-		<set name="export.selector.target" value="EXPORT"/>
-		<set name="bitmap.selector.iface" value="\.(bitmap|extension|mifconv)$"/>
-		<set name="bitmap.selector.target" value="BITMAP"/>
-		<set name="resource_deps.selector.iface" value="\.resource$"/>
-		<set name="resource_deps.selector.target" value="RESOURCE_DEPS"/>
-		<set name="resource_deps.selector.ignoretargets" value="^(RESOURCE|CLEAN|CLEANEXPORT|REALLYCLEAN)$"/>
-		<set name="resource.selector.iface" value="\.(resource|extension|mif2cdlindex|nativejava)$"/>
-		<set name="resource.selector.target" value="RESOURCE"/>
-		<set name="default.selector.iface" value="\.(?!export$|bitmap$|resource$|mifconv$|mif2cdlindex$|nativejava$).*$"/>
-		<set name="default.selector.target" value="ALL"/>
-
-		<!-- is the text output with -j buffered or scrambled? -->
-		<set name="scrambled" value="true"/>
-	</var>
-	
-	<alias name="make" meaning="make_engine"/>
-
-	<!-- use the talon shell -->
-	<var name="make_no_talon_engine" extends="make_engine">
-	        <set name='DEFAULT_SHELL' value='$(SBS_SHELL)' type='tool'/>
-	        <set name='USE_TALON' value=''/>
-	</var>
-
-	<alias name="make_no_talon" meaning="make_no_talon_engine"/>
-
-	<!-- other derived versions of GNU make -->
-
-	<!-- Raptor make engine for Electric Make -->
-	<var name="emake_engine" extends="make_engine">
-		<env name="EMAKE" default="emake" type="tool" versionCommand="$(EMAKE) --version " versionResult="Electric Make version (4\.[2-9])|([56789]\.[0-9])"/>
-		<set name="build" value="$(EMAKE) HAVE_ORDERONLY= -r"/>
-		<set name="scrambled" value="false"/>
-		<set name='TALON_DESCRAMBLE' value=''/>
-	</var>
-
-	<alias name="emake" meaning="emake_engine"/>
-	
-	<!-- use the talon shell -->
-	<var name="emake_no_talon_engine" extends="emake_engine">
-	        <set name='DEFAULT_SHELL' value='$(SBS_SHELL)' type='tool'/>
-	        <set name='USE_TALON' value=''/>
-	</var>
-
-	<alias name="emake_no_talon" meaning="emake_no_talon_engine"/>
-	
-	<!-- Raptor make engine for PVMgmake -->
-	<var name="pvmgmake_engine" extends="make_engine">
-		<env name="PVMGMAKE" default="pvmgmake" type="tool" versionCommand="$(PVMGMAKE) --version " versionResult="PVMGmake-([0-9]\.[0-9])|(0.) rpt"/>
-		<set name="build" value="$(PVMGMAKE) HAVE_ORDERONLY=true  -r"/>
-		<set name="scrambled" value="false" />
-		<set name='TALON_DESCRAMBLE' value=''/>
-	</var>
-
-	<alias name="pvmgmake" meaning="pvmgmake_engine"/>
-
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- Some common Raptor make engines -->
+	
+	<!-- Raptor make engine for GNU make -->
+	<var name="make_engine">
+		<varRef ref="default.locations"/>
+
+		<!-- Shell settings -->
+		<set name='DEFAULT_SHELL' value='$(SBS_HOME)/$(HOSTPLATFORM_DIR)/bin/talon$(DOTEXE)' type='tool'/>
+		<set name='TALON_SHELL' value='$(SBS_SHELL)' type='tool'/>
+		<set name='USE_TALON' value='1'/>
+		<set name='TALON_TIMEOUT' value='600000'/>
+		<set name='TALON_DESCRAMBLE' value='1'/>
+		
+		<!-- Work around for RVCT compile failures -->
+		<set name='DELETE_ON_FAILED_COMPILE' value='1'/>
+		
+		<!-- Command-line for initialisation -->
+		<set name="initialise" value=""/>
+
+		<!-- Command-line for shutdown -->
+		<set name="shutdown" value=""/>
+
+		<!-- Command-line for build  -->
+		<set name="build" value="$(GNUMAKE38) HAVE_ORDERONLY=1 -r" type="tool"/>
+
+		<!-- Options  -->
+		<set name="makefile" value="-f"/>
+		<set name="keep_going" value="-k"/>
+		<set name="jobs" value="-j"/>
+		
+		<!-- The following are stuck on the commandline before any options
+		     specified by the sbs "mo" option, so they can be overridden -->
+		<set name="defaultoptions" value=""/>
+
+		<!-- How to split out the makefiles -->
+		<set name="selectors" value="export,bitmap,resource_deps,resource,default"/>
+		<set name="export.selector.iface" value="\.export$"/>
+		<set name="export.selector.target" value="EXPORT"/>
+		<set name="bitmap.selector.iface" value="\.(bitmap|extension|mifconv)$"/>
+		<set name="bitmap.selector.target" value="BITMAP"/>
+		<set name="resource_deps.selector.iface" value="\.resource$"/>
+		<set name="resource_deps.selector.target" value="RESOURCE_DEPS"/>
+		<set name="resource_deps.selector.ignoretargets" value="^(RESOURCE|CLEAN|CLEANEXPORT|REALLYCLEAN)$"/>
+		<set name="resource.selector.iface" value="\.(resource|extension|mif2cdlindex|nativejava)$"/>
+		<set name="resource.selector.target" value="RESOURCE"/>
+		<set name="default.selector.iface" value="\.(?!export$|bitmap$|resource$|mifconv$|mif2cdlindex$|nativejava$).*$"/>
+		<set name="default.selector.target" value="ALL"/>
+
+		<!-- is the text output with -j buffered or scrambled? -->
+		<set name="scrambled" value="true"/>
+
+		<!-- workaround for damaged log output from emake -->
+		<set name="copylogfromannofile" value="false"/>
+	</var>
+	
+	<alias name="make" meaning="make_engine" type="engine"/>
+
+	<!-- use the talon shell -->
+	<var name="make_no_talon_engine" extends="make_engine">
+	        <set name='DEFAULT_SHELL' value='$(SBS_SHELL)' type='tool'/>
+	        <set name='USE_TALON' value=''/>
+	</var>
+
+	<alias name="make_no_talon" meaning="make_no_talon_engine" type="engine"/>
+
+	<!-- other derived versions of GNU make -->
+
+	<!-- Raptor make engine for Electric Make -->
+	<var name="emake_engine" extends="make_engine">
+		<env name="EMAKE" default="emake" type="tool" versionCommand="$(EMAKE) --version " versionResult="Electric Make version (4\.[2-9])|([56789]\.[0-9])"/>
+		<set name="build" value="$(EMAKE) HAVE_ORDERONLY= -r"/>
+		<set name="scrambled" value="false"/>
+		<set name='TALON_DESCRAMBLE' value=''/>
+		<set name='DELETE_ON_FAILED_COMPILE' value=''/>
+
+		<!-- workaround for damaged log output from emake -->
+		<set name="copylogfromannofile" value="true"/>
+	</var>
+
+	<alias name="emake" meaning="emake_engine" type="engine"/>
+	
+	<!-- use the talon shell -->
+	<var name="emake_no_talon_engine" extends="emake_engine">
+	        <set name='DEFAULT_SHELL' value='$(SBS_SHELL)' type='tool'/>
+	        <set name='USE_TALON' value=''/>
+	</var>
+
+	<alias name="emake_no_talon" meaning="emake_no_talon_engine" type="engine"/>
+	
+	<!-- Raptor make engine for PVMgmake -->
+	<var name="pvmgmake_engine" extends="make_engine">
+		<env name="PVMGMAKE" default="pvmgmake" type="tool" versionCommand="$(PVMGMAKE) --version " versionResult="PVMGmake-([0-9]\.[0-9])|(0.) rpt"/>
+		<set name="build" value="$(PVMGMAKE) HAVE_ORDERONLY=true  -r"/>
+		<set name="scrambled" value="false" />
+		<set name='TALON_DESCRAMBLE' value=''/>
+		<set name='DELETE_ON_FAILED_COMPILE' value=''/>
+	</var>
+
+	<alias name="pvmgmake" meaning="pvmgmake_engine" type="engine"/>
+
+</build>
--- a/sbsv2/raptor/lib/config/meta.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/meta.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,8 +1,8 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- Configuration for metadata processing  -->
-
-	<var name="meta">
-		<varRef ref="default.locations"/>
-	</var>
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- Configuration for metadata processing  -->
+
+	<var name="meta">
+		<varRef ref="default.locations"/>
+	</var>
+</build>
--- a/sbsv2/raptor/lib/config/msvc.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/msvc.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,102 +1,104 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- build configurations for MSVC compilers -->
-	<var name="tools_base" extends="root">
-		<varRef ref="default.interfaces"/>
-		<varRef ref="default.locations"/>
-
-		<!-- picked up from the Environment -->
-		<env name='MS_CL' default='cl.exe' type='tool' versionCommand='$(MS_CL)' versionResult='Version 12\.[0-9]{2}\.[0-9]{4}'/>
-		<env name='MS_LINK' default='link.exe' type='tool' versionCommand='$(MS_LINK)' versionResult='Version 6\.[0-9]{2}.[0-9]{4}'/>
-		<env name='MS_LIB' default='lib.exe' type='tool' versionCommand='$(MS_LIB)' versionResult='Version 6\.[0-9]{2}.[0-9]{4}'/>
-		<env name='MS_BSCMAKE' default='bscmake.exe' type='tool' versionCommand='$(MS_BSCMAKE)' versionResult='Version 6\.[0-9]{2}.[0-9]{4}'/>
-
-		<!-- MS toolchain environment variables -->
-		<env name='INCLUDE'/>
-		<env name='LIB'/>
-
-		<!-- link to bld.inf and mmp platform names -->
-		<set name='TRADITIONAL_PLATFORM' value='TOOLS'/>
-		<set name='NMAKE' value='nmake'/>
-		<set name='NMAKEFLAGS' value='-nologo -x - '/>
-		<!-- tools options -->
-		<set name='OPT.BROWSEDB' value='-o'/>
-		<set name='OPT.BROWSEFILE' value='-FR'/>
-		<set name='OPT.COMPILE' value='-c '/>
-		<set name='OPT.DEFINE' value='-D '/>
-		<set name='OPT.INCLUDE' value='-I '/>
-		<set name='OPT.IMPLIB' value='-implib:'/>
-		<set name='OPT.LIBDEB' value='-MTd '/>
-		<set name='OPT.LIBREL' value='-MT '/>
-		<set name='OPT.LISTING' value='-Fa'/>
-		<set name='OPT.NOLOGO' value='-nologo'/>
-		<set name='OPT.OBJECTFILE' value='-Fo'/>
-		<set name='OPT.OUTFILE' value='-out:'/>
-		<set name='OPT.PDBFILE' value='-Fd'/>
-		<set name='OPT.PREINCLUDE' value='-FI '/>
-		<set name='OPT.SUBSYSTEM' value='-subsystem:'/>
-		<set name='OPT.SYSINCLUDE' value='-I '/>
-		<set name='OPT.USERINCLUDE' value='-I '/>
-		<set name='PREFIX.RESPONSEFILE' value='@'/>
-		<set name='CC' value='$(MS_CL)'/>
-		<set name='CDEFS' value='__SYMBIAN32__ __VC32__ __TOOLS__ __MSVC6__ __MSVC600__ WIN32 WINDOWS __SUPPORT_CPP_EXCEPTIONS__ $(MMPDEFS)'/>
-		<set name='CDEFS.DEB' value='_DEBUG'/>
-		<set name='CDEFS.REL' value='NDEBUG'/>
-		<set name='CFLAGS' value='$(OPT.COMPILE) $(OPT.NOLOGO) -Zp4 -GF'/>
-		<set name='CFLAGS.DEFAULT.WARNLEVEL' value='-W4'/>
-		<set name='CFLAGS.DEB' value='-Zi -Od'/>
-		<set name='CFLAGS.REL' value='-O1 -Op'/>
-		<set name='SHAREDFLAGS' value='kernel32.lib $(OPT.NOLOGO) -machine:IX86  -ignore:4089 -ignore:4005 -ignore:4098'/>
-		<set name='LD' value='$(MS_LINK)'/>
-		<set name='LFLAGS' value='$(SHAREDFLAGS) -WARN:1'/>
-		<set name='LFLAGS.DEB' value='-debug'/>
-		<set name='LFLAGS.REL' value='-incremental:no'/>
-		<set name='AR' value='$(MS_LIB)'/>
-		<set name='ARFLAGS' value='$(SHAREDFLAGS)'/>
-		<set name='BROWSETOOL' value='$(MS_BSCMAKE)'/>
-		<set name='BROWSEFLAGS' value='$(OPT.NOLOGO)'/>
-		<set name='PLATMACROS.WINDOWS' value='VC32 TOOLS MSVC6 MSVC600'/>
-		<set name='PLATMACROS.LINUX' value='$(PLATMACROS.WINDOWS)'/>
-		<!-- interfaces -->
-		<set name="INTERFACE.exe" value="msvctools.exe"/>
-		<set name="INTERFACE.lib" value="msvctools.lib"/>
-
-		<set name='RELEASEPATHROOT' value='$(EPOCROOT)/epoc32/release'/>
-		<set name='IMPORTLIBPATH' value='$(RELEASEPATHROOT)/tools/udeb'/>
-
-		<set name='MMPDEFS' value=''/>
-		<set name='OUTPUTPATH' value='$(SBS_BUILD_DIR)'/>
-		<set name='SBSV1MAKE' value='$(EPOCROOT)/epoc32/tools/make$(DOTEXE)'/>
-		<set name='SYSTEMINCLUDE' value=''/>
-		<set name='TARGET' value='TARGET_WAS_NOT_SET_PROPERLY'/>
-		<set name='TARGETPATH' value=''/>
-		<set name='TARGETTYPE' value='TARGETTYPE_WAS_NOT_SET_PROPERLY'/>
-		<set name='USERINCLUDE' value=''/>
-		<set name='VARIANTPLATFORM' value='tools'/>
-	</var>
-
-	<var name="tools_deb" extends="tools_base">
-		<set name='FULLVARIANTPATH' value='tools/deb'/>
-		<set name='VARIANTTYPE' value='deb'/>
-		<set name='INSTALLPATH' value=''/> <!-- don't install DEB builds  -->
-		<append name='CDEFS' value='$(CDEFS.DEB)'/>
-		<append name='CFLAGS' value='$(CFLAGS.DEB)'/>
-		<append name='LFLAGS' value='$(LFLAGS.DEB)'/>
-		<set name='CFLAGS.LIB' value='$(OPT.LIBDEB)'/>
-	</var>
-
-	<var name="tools_rel" extends="tools_base">
-		<set name='FULLVARIANTPATH' value='tools/rel'/>
-		<set name='VARIANTTYPE' value='rel'/>
-		<set name='INSTALLPATH' value='$(EPOCROOT)/epoc32/tools'/>
-		<append name='CDEFS' value='$(CDEFS.REL)'/>
-		<append name='CFLAGS' value='$(CFLAGS.REL)'/>
-		<append name='LFLAGS' value='$(LFLAGS.REL)'/>
-		<set name='CFLAGS.LIB' value='$(OPT.LIBREL)'/>
-	</var>
-
-	<group name='tools'>
-		<varRef ref='tools_rel'/>
-		<varRef ref='tools_deb'/>
-	</group>
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- build variants for MSVC toolchains -->
+	<var name="tools_base" extends="root">
+		<varRef ref="default.interfaces"/>
+		<varRef ref="default.locations"/>
+
+		<!-- toolchain tools -->
+		<env name='MS_CL' default='cl.exe' type='tool' versionCommand='$(MS_CL)' versionResult='Version 12\.[0-9]{2}\.[0-9]{4}'/>
+		<env name='MS_LINK' default='link.exe' type='tool' versionCommand='$(MS_LINK)' versionResult='Version 6\.[0-9]{2}.[0-9]{4}'/>
+		<env name='MS_LIB' default='lib.exe' type='tool' versionCommand='$(MS_LIB)' versionResult='Version 6\.[0-9]{2}.[0-9]{4}'/>
+		<env name='MS_BSCMAKE' default='bscmake.exe' type='tool' versionCommand='$(MS_BSCMAKE)' versionResult='Version 6\.[0-9]{2}.[0-9]{4}'/>
+
+		<!-- MS toolchain environment variables -->
+		<env name='INCLUDE'/>
+		<env name='LIB'/>
+
+		<!-- link to bld.inf and mmp platform names -->
+		<set name='TRADITIONAL_PLATFORM' value='TOOLS'/>
+
+		<!-- interfaces -->
+		<set name="INTERFACE.exe" value="msvctools.exe"/>
+		<set name="INTERFACE.lib" value="msvctools.lib"/>		
+		
+		<set name='NMAKE' value='nmake'/>
+		<set name='NMAKEFLAGS' value='-nologo -x - '/>
+		
+		<!-- tools options -->
+		<set name='OPT.BROWSEDB' value='-o'/>
+		<set name='OPT.BROWSEFILE' value='-FR'/>
+		<set name='OPT.COMPILE' value='-c '/>
+		<set name='OPT.DEFINE' value='-D '/>
+		<set name='OPT.INCLUDE' value='-I '/>
+		<set name='OPT.IMPLIB' value='-implib:'/>
+		<set name='OPT.LIBDEB' value='-MTd '/>
+		<set name='OPT.LIBREL' value='-MT '/>
+		<set name='OPT.LISTING' value='-Fa'/>
+		<set name='OPT.NOLOGO' value='-nologo'/>
+		<set name='OPT.OBJECTFILE' value='-Fo'/>
+		<set name='OPT.OUTFILE' value='-out:'/>
+		<set name='OPT.PREINCLUDE' value='-FI '/>
+		<set name='OPT.SUBSYSTEM' value='-subsystem:'/>
+		<set name='OPT.SYSINCLUDE' value='-I '/>
+		<set name='OPT.USERINCLUDE' value='-I '/>
+		<set name='PREFIX.RESPONSEFILE' value='@'/>
+		<set name='CC' value='$(MS_CL)'/>
+		<set name='CDEFS' value='__SYMBIAN32__ __VC32__ __TOOLS__ __MSVC6__ __MSVC600__ WIN32 WINDOWS __SUPPORT_CPP_EXCEPTIONS__ $(MMPDEFS)'/>
+		<set name='CDEFS.DEB' value='_DEBUG'/>
+		<set name='CDEFS.REL' value='NDEBUG'/>
+		<set name='CFLAGS' value='$(OPT.COMPILE) $(OPT.NOLOGO) -Zp4 -GF'/>
+		<set name='CFLAGS.DEFAULT.WARNLEVEL' value='-W4'/>
+		<set name='CFLAGS.DEB' value='-Od'/>
+		<set name='CFLAGS.REL' value='-O1 -Op'/>
+		<set name='SHAREDFLAGS' value='kernel32.lib $(OPT.NOLOGO) -machine:IX86  -ignore:4089 -ignore:4005 -ignore:4098'/>
+		<set name='LD' value='$(MS_LINK)'/>
+		<set name='LFLAGS' value='$(SHAREDFLAGS) -WARN:1'/>
+		<set name='LFLAGS.DEB' value='-debug'/>
+		<set name='LFLAGS.REL' value='-incremental:no'/>
+		<set name='AR' value='$(MS_LIB)'/>
+		<set name='ARFLAGS' value='$(SHAREDFLAGS)'/>
+		<set name='BROWSETOOL' value='$(MS_BSCMAKE)'/>
+		<set name='BROWSEFLAGS' value='$(OPT.NOLOGO)'/>
+		<set name='PLATMACROS.WINDOWS' value='VC32 TOOLS MSVC6 MSVC600'/>
+		<set name='PLATMACROS.LINUX' value='$(PLATMACROS.WINDOWS)'/>
+
+		<set name='RELEASEPATHROOT' value='$(EPOCROOT)/epoc32/release'/>
+		<set name='IMPORTLIBPATH' value='$(RELEASEPATHROOT)/tools/udeb'/>
+
+		<set name='MMPDEFS' value=''/>
+		<set name='OUTPUTPATH' value='$(SBS_BUILD_DIR)'/>
+		<set name='SBSV1MAKE' value='$(EPOCROOT)/epoc32/tools/make$(DOTEXE)'/>
+		<set name='SYSTEMINCLUDE' value=''/>
+		<set name='TARGET' value='TARGET_WAS_NOT_SET_PROPERLY'/>
+		<set name='TARGETPATH' value=''/>
+		<set name='TARGETTYPE' value='TARGETTYPE_WAS_NOT_SET_PROPERLY'/>
+		<set name='USERINCLUDE' value=''/>
+		<set name='VARIANTPLATFORM' value='tools'/>
+	</var>
+
+	<var name="tools_deb" extends="tools_base">
+		<set name='FULLVARIANTPATH' value='tools/deb'/>
+		<set name='VARIANTTYPE' value='deb'/>
+		<set name='INSTALLPATH' value=''/> <!-- don't install DEB builds  -->
+		<append name='CDEFS' value='$(CDEFS.DEB)'/>
+		<append name='CFLAGS' value='$(CFLAGS.DEB)'/>
+		<append name='LFLAGS' value='$(LFLAGS.DEB)'/>
+		<set name='CFLAGS.LIB' value='$(OPT.LIBDEB)'/>
+	</var>
+
+	<var name="tools_rel" extends="tools_base">
+		<set name='FULLVARIANTPATH' value='tools/rel'/>
+		<set name='VARIANTTYPE' value='rel'/>
+		<set name='INSTALLPATH' value='$(EPOCROOT)/epoc32/tools'/>
+		<append name='CDEFS' value='$(CDEFS.REL)'/>
+		<append name='CFLAGS' value='$(CFLAGS.REL)'/>
+		<append name='LFLAGS' value='$(LFLAGS.REL)'/>
+		<set name='CFLAGS.LIB' value='$(OPT.LIBREL)'/>
+	</var>
+
+	<group name='tools'>
+		<varRef ref='tools_rel'/>
+		<varRef ref='tools_deb'/>
+	</group>
+</build>
--- a/sbsv2/raptor/lib/config/root.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/root.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,53 +1,56 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-
-	<!-- 
-	
-	The root variant is extended by all buildable variants.
-	
-	It contains references to variants which have defaults here but which
-	can be overridden to effectively apply a global change for all builds. 
-	
-	-->
-
-	<var name="root">
-		<varRef ref="root.places"/>
-		<varRef ref="root.properties"/>
-		
-		<!-- redefine this to make changes to the root variant -->
-		<varRef ref="root.changes"/>
-	</var>
-
-	<!-- Common folders and files -->
-	<var name="root.places">
-		<env name='EPOCROOT' default='/' type='path'/>
-		
-		<set name='EPOCINCLUDE' value='$(EPOCROOT)/epoc32/include'/>
-		<set name='EPOCTOOLS' value='$(EPOCROOT)/epoc32/tools'/>
-
-		<!-- Place where intermediate files are built -->
-		<env name='SBS_BUILD_DIR' default='$(EPOCROOT)/epoc32/build' type='path'/> 
-
-		<!-- Configuration files and directories -->
-		<set name='PRODUCT_INCLUDE' value='$(EPOCINCLUDE)/variant/symbian_os.hrh'/>
-		<set name='VARIANT_CFG' value='$(EPOCTOOLS)/variant/variant.cfg'/>
-		<set name='MAKEFILE_TEMPLATES' value='$(EPOCTOOLS)/makefile_templates'/>
-		<set name='FLM_EXPORT_DIR' value='$(MAKEFILE_TEMPLATES)'/>
-	</var>
-	
-	<!-- Things which are properties of different OS versions rather than
-		 properties of Raptor itself. The values here are for TB92sf and
-		 may be completely redefined for other OS versions or modified
-		 slightly by redefining the root.changes variant. -->
-	<var name="root.properties">
-		<set name='POSTLINKER_SUPPORTS_WDP' value='1'/>
-		<set name='SUPPORTS_STDCPP_NEWLIB' value='1'/>
-		<set name="RVCT_PRE_INCLUDE" value="$(EPOCINCLUDE)/rvct/rvct.h"/>
-	</var>
-	
-	<!-- Placeholder for the root.changes variant. This will typically be
-	     redefined inside a .xml file in the $(EPOCROOT)/epoc32/sbs_config
-	     folder or a folder added with the configpath option. -->
-	<var name="root.changes"/>
-	
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+
+	<!-- 
+	
+	The root variant is extended by all buildable variants.
+	
+	It contains references to variants which have defaults here but which
+	can be overridden to effectively apply a global change for all builds. 
+	
+	-->
+
+	<var name="root">
+		<env name='FLMDEBUG' default=''/>	
+	
+		<varRef ref="root.places"/>
+		<varRef ref="root.properties"/>
+		
+		<!-- redefine this to make changes to the root variant -->
+		<varRef ref="root.changes"/>
+	</var>
+
+	<!-- Common folders and files -->
+	<var name="root.places">
+		<env name='EPOCROOT' default='/' type='path'/>
+		
+		<set name='EPOCINCLUDE' value='$(EPOCROOT)/epoc32/include'/>
+		<set name='EPOCTOOLS' value='$(EPOCROOT)/epoc32/tools'/>
+
+		<!-- Place where intermediate files are built -->
+		<env name='SBS_BUILD_DIR' default='$(EPOCROOT)/epoc32/build' type='path'/> 
+
+		<!-- Configuration files and directories -->
+		<set name='PRODUCT_INCLUDE' value='$(EPOCINCLUDE)/variant/symbian_os.hrh'/>
+		<set name='VARIANT_CFG' value='$(EPOCTOOLS)/variant/variant.cfg'/>
+		<set name='MAKEFILE_TEMPLATES' value='$(EPOCTOOLS)/makefile_templates'/>
+		<set name='FLM_EXPORT_DIR' value='$(MAKEFILE_TEMPLATES)'/>
+	</var>
+	
+	<!-- Things which are properties of different OS versions rather than
+		 properties of Raptor itself. The values here are for TB92sf and
+		 may be completely redefined for other OS versions or modified
+		 slightly by redefining the root.changes variant. -->
+	<var name="root.properties">
+		<set name='POSTLINKER_SUPPORTS_WDP' value='1'/>
+		<set name='SUPPORTS_STDCPP_NEWLIB' value='1'/>
+		<set name="RVCT_PRE_INCLUDE" value="$(EPOCINCLUDE)/rvct/rvct.h"/>
+		<set name="SUPPORTS_ABIV1_IMPLIBS" value=''/>
+	</var>
+	
+	<!-- Placeholder for the root.changes variant. This will typically be
+	     redefined inside a .xml file in the $(EPOCROOT)/epoc32/sbs_config
+	     folder or a folder added with the configpath option. -->
+	<var name="root.changes"/>
+	
+</build>
--- a/sbsv2/raptor/lib/config/rvct.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/rvct.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,107 +1,110 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- RVCT build variant for RVCT compilers -->
-	<var name="rvct">
-		<set name="TOOLCHAIN" value="RVCT"/>
-		<set name="CC" value="$(ARMCC)"/>
-		<set name="LD" value="$(ARMLD)"/>
-		<set name="ASM" value="$(ARMASM)"/>
-		<set name="AR" value="$(ARMAR)"/>	
-		<set name="ARMCC" value="$(RVCTBIN)/armcc$(DOTEXE)"/>
-		<set name="ARMLD" value="$(RVCTBIN)/armlink$(DOTEXE)"/>
-		<set name="ARMASM" value="$(RVCTBIN)/armasm$(DOTEXE)"/>
-		<set name="ARMAR" value="$(RVCTBIN)/armar$(DOTEXE)"/>
-		<set name="FROMELF" value="$(RVCTBIN)/fromelf$(DOTEXE)"/>
-		<set name="AAPCS_OPTION" value="--apcs /inter"/>
-		<set name="ARCHIVER_CREATE_OPTION" value="--create"/>
-		<set name="ARM_INSTRUCTION_SET" value="--arm"/>
-		<set name="ASM_OUTPUT_OPTION" value="-o"/>
-		<set name="ASSEMBLER_LISTING_OPTION" value="-S"/>
-		<set name="BPABI_OPTION" value="--bpabi"/>
-		<set name="CC_ERRORS_CONTROL_OPTION" value="--diag_error 1267"/>
-		<set name="CC_WARNINGS_CONTROL_OPTION" value="--diag_suppress 161,611,654,997,1152,1300,1464,1488,2523,6318,6331"/>
-		<set name="C_LANG_OPTION" value=""/>
-		<set name="COMMANDFILE_OPTION" value="--via "/>
-		<set name="COMPILE_ONLY_OPTION" value="-c"/>
-		<set name="CPP_LANG_OPTION" value="--cpp"/>
-		<set name="DEBUG_OPTIMISATION" value="-O0"/>
-		<set name="DEPEND_OPTION" value="--depend_format=unix --depend"/>
-		<set name="ENUM_OPTION" value="--enum_is_int"/>
-		<set name="EXPORT_VTBL_OPTION" value="--export_all_vtbl"/>
-		<set name="EXTRA_LD_OPTION" value="--datacompressor=off"/>
-		<set name="FPMODE_OPTION" value="--fpmode ieee_no_fenv"/>
-		<set name="LD_ERRORS_CONTROL_OPTION" value=""/>
-		<set name="LD_WARNINGS_CONTROL_OPTION" value="--diag_suppress 6331"/>
-		<set name="LISTING_OPTION" value="-S"/>
-		<set name="EXCEPTIONS" value="--exceptions --exceptions_unwind"/>
-		<set name="NO_EXCEPTIONS" value="--no_exceptions --no_exceptions_unwind"/>
-		<set name="PREINCLUDE_OPTION" value="--preinclude"/>
-		<set name="PREPROCESSOR_OPTION" value="-E"/>
-		<set name="REL_OPTIMISATION" value="-O2"/>
-		<set name="STDLIB_OPTION" value="--no_scanlib"/>
-		<set name="RUNTIME_SYMBOL_VISIBILITY_OPTION" value="--dllimport_runtime"/>
-		<set name="RW_BASE_OPTION" value="--rw-base"/>
-		<set name="CODE_SEGMENT_START" value=""/>
-		<set name="PREINCLUDE" value="$(RVCT_PRE_INCLUDE)"/>
-		<set name="CC.DWARF2" value="--dwarf2"/>
-		<set name="CC.DWARF3" value="--dwarf3"/>
-		<set name="LD.ARMV5" value=""/>
-		<set name="LD.ARMV6" value=""/>
-		<set name="LD.ARMV7" value=""/>
-		<set name="ARMMACROS.VAR" value=""/>
-		<set name="CFLAGS" value=""/>
-		<set name="CIADEFS" value="__CIA__"/>
-		<append name="CDEFS" value='__SUPPORT_CPP_EXCEPTIONS__ _UNICODE __SYMBIAN32__ __ARMCC__ __EPOC32__ __MARM__ __EABI__ __PRODUCT_INCLUDE__="$(PRODUCT_INCLUDE)" $(MMPDEFS) $(ARMMACROS)'/>
-		<set name="COMPILER_CIA_FLAGS" value=""/>
-		<set name="COMPILER_FPU_FLAGS" value="--fpu $(ARMFPU)"/>	
-		<set name="COMPILER_DEFINES" value=""/>
-		<set name="COMPILER_INTERWORK_DEFINES" value="__MARM_INTERWORK__"/>
-		<set name="COMPILER_SYSTEM_INCLUDE_OPTION" value="-J"/>
-		<set name="COMPILER_THUMB_DEFINES" value="__MARM_THUMB__"/>
-		<set name="DATA_SEGMENT_START" value="$(SPLIT_OPTION) $(RW_BASE_OPTION)"/>
-		<set name="EXTRA_CC_OPTION" value=""/>
-		<set name="HEADER_FILES_CONTROL_OPTION" value=""/>
-		<set name="LIBPATH" value=""/>
-		<set name="LIBRARY" value=""/>
-		<set name="LICENSERETRY_OPTION" value=""/>
-		<set name="LINKER_ADD_STATIC_RUNTIME" value=""/>		
-		<set name="LINKER_DEBUG_OPTION" value="--debug"/>
-		<set name="LINKER_DEFAULT_LIBS" value=""/>
-		<set name="LINKER_DEFAULT_LIB_PATHS" value=""/>
-		<set name="LINKER_ENTRY_OPTION" value="--entry"/>
-		<set name="LINKER_GROUP_START_OPTION" value=""/>
-		<set name="LINKER_GROUP_END_OPTION" value=""/>
-		<set name="LINKER_MISC_FLAGS" value="$(LICENSERETRY_OPTION)"/>
-		<set name="LINKER_NODEBUG_OPTION" value=""/>
-		<set name="LINKER_SCRIPT_FILE_OPTION" value=""/>
-		<set name="LINKER_SYMBOLS_OPTION" value="--symbols"/>
-		<set name="LINKER_SYMBOLS_FILE_OPTION" value="--list"/>
-		<set name="SHARED_OBJECT_OPTION" value="--dll"/>
-		<set name="SID" value=""/>
-		<set name="SO_NAME_OPTION" value="--soname"/>
-		<set name="STATIC_LIBS_PATH" value="$(RVCTLIB)/armlib"/>
-		<set name="STDCPP_INCLUDE" value="$(EPOCINCLUDE)/stdapis"/>
-		<set name="SYMBIAN_LD_MESSAGE_OPTION" value="$(LD_WARNINGS_CONTROL_OPTION) $(LD_ERRORS_CONTROL_OPTION)"/>
-		<set name="SUPPORTS_ABIV1_IMPLIBS" value="1"/>		
-		<set name="TARGET_RELOCATION_OPTION" value="" />
-		<set name="SYMVER_OPTION" value="--symver_soname"/>
-		<set name="TEMP_FILES_OPTION" value=""/>
-		<set name="THUMB_INSTRUCTION_SET" value="--thumb"/>
-		<set name="INSTRUCTION_SET" value=""/>
-		<set name="TRANASM_FLAGS" value="-n -s"/>
-		<set name="TRANASM_INPUT_OPTION" value=""/>
-		<set name="TRANASM_OUTPUT_OPTION" value="-o="/>
-		<set name="TRANSFORM_CIA" value="1"/>
-		<set name="UNDEFINED_SYMBOL_REF_OPTION" value=""/>
-		<set name="UNIX_SLASH_FOR_CC_ABS_PATHS" value="0"/>
-		<set name="UNRESOLVED_SYMBOL_REF_OPTION" value=""/>
-		<set name="USERINCLUDE" value=""/>
-		<set name="USER_LIBS_PATH_OPTION" value="--userlibpath"/>
-		<set name="VFE_OPTION" value="--no_vfe"/>
-		<set name="PLATMACROS.WINDOWS" value="ARMCC EPOC32 MARM EABI GENERIC_MARM MARM_ARMV5 $(PLATMACROS.CONFIG) $(PLATMACROS.VAR)"/>
-		<set name="PLATMACROS.LINUX" value="$(PLATMACROS.WINDOWS)"/>
-		<set name="PLATMACROS.CONFIG" value=""/>
-		<set name="PLATMACROS.VAR" value=""/>
-		<set name="NO_UNALIGNED_ACCESS" value="$(CC.NO_UNALIGNED_ACCESS)"/>
-	</var>
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- build variant for RVCT ARM toolchains -->
+	<var name="rvct">
+		<set name="TOOLCHAIN" value="RVCT"/>
+		<set name="PLATMACROS.TOOLCHAIN" value="ARMCC"/>
+	
+		<!-- toolchain tools -->
+		<set name="ARMAR" value="$(RVCTBIN)/armar$(DOTEXE)"/>
+		<set name="ARMASM" value="$(RVCTBIN)/armasm$(DOTEXE)"/>
+		<set name="ARMCC" value="$(RVCTBIN)/armcc$(DOTEXE)"/>
+		<set name="ARMLD" value="$(RVCTBIN)/armlink$(DOTEXE)"/>
+		<set name="FROMELF" value="$(RVCTBIN)/fromelf$(DOTEXE)"/>
+		
+		<set name="CC" value="$(ARMCC)"/>
+		<set name="LD" value="$(ARMLD)"/>
+		<set name="ASM" value="$(ARMASM)"/>
+		<set name="AR" value="$(ARMAR)"/>	
+	
+		<set name="AAPCS_OPTION" value="--apcs /inter"/>
+		<set name="ARCHIVER_CREATE_OPTION" value="--create"/>
+		<set name="ARM_INSTRUCTION_SET" value="--arm"/>
+		<set name="ASM_OUTPUT_OPTION" value="-o"/>
+		<set name="ASSEMBLER_LISTING_OPTION" value="-S"/>
+		<set name="BPABI_OPTION" value="--bpabi"/>
+		<set name="CC.DWARF2" value="--dwarf2"/>
+		<set name="CC.DWARF3" value="--dwarf3"/>
+		<set name="CC_ERRORS_CONTROL_OPTION" value="--diag_error 1267"/>
+		<set name="CC_WARNINGS_CONTROL_OPTION" value="--diag_suppress 161,611,654,997,1152,1300,1464,1488,2523,6318,6331"/>
+		<set name="CFLAGS" value=""/>
+		<set name="CIADEFS" value="__CIA__"/>
+		<set name="CODE_SEGMENT_START" value=""/>
+		<set name="COMMANDFILE_OPTION" value="--via "/>
+		<set name="COMPILER_CIA_FLAGS" value=""/>
+		<set name="COMPILER_DEFINES" value=""/>
+		<set name="COMPILER_FPU_OPTION" value="--fpu "/>
+		<set name="COMPILER_INTERWORK_DEFINES" value="__MARM_INTERWORK__"/>
+		<set name="COMPILER_SYSTEM_INCLUDE_OPTION" value="-J"/>
+		<set name="COMPILER_THUMB_DEFINES" value="__MARM_THUMB__"/>
+		<set name="COMPILE_ONLY_OPTION" value="-c"/>
+		<set name="CPP_LANG_OPTION" value="--cpp"/>
+		<set name="C_LANG_OPTION" value=""/>
+		<set name="DATA_SEGMENT_START" value="$(SPLIT_OPTION) $(RW_BASE_OPTION)"/>
+		<set name="DEBUG_OPTIMISATION" value="-O0"/>
+		<set name="DEPEND_OPTION" value="--depend_format=unix --depend"/>
+		<set name="ENUM_OPTION" value="--enum_is_int"/>
+		<set name="EXCEPTIONS" value="--exceptions --exceptions_unwind"/>
+		<set name="EXPORT_VTBL_OPTION" value="--export_all_vtbl"/>
+		<set name="EXTRA_CC_OPTION" value=""/>
+		<set name="EXTRA_LD_OPTION" value="--datacompressor=off"/>
+		<set name="FPMODE_OPTION" value="--fpmode ieee_no_fenv"/>
+		<set name="HEADER_FILES_CONTROL_OPTION" value=""/>
+		<set name="INSTRUCTION_SET" value=""/>
+		<set name="LD.ARMV5" value=""/>
+		<set name="LD.ARMV6" value=""/>
+		<set name="LD.ARMV7" value=""/>
+		<set name="LD_ERRORS_CONTROL_OPTION" value=""/>
+		<set name="LD_WARNINGS_CONTROL_OPTION" value="--diag_suppress 6331"/>
+		<set name="LD_WARNINGS_SUPPRESSION_ARMLIBS" value="--diag_suppress 6780"/>
+		<set name="LIBPATH" value=""/>
+		<set name="LIBRARY" value=""/>
+		<set name="LICENSERETRY_OPTION" value=""/>
+		<set name="LINKER_ADD_STATIC_RUNTIME" value=""/>		
+		<set name="LINKER_DEBUG_OPTION" value="--debug"/>
+		<set name="LINKER_DEFAULT_LIBS" value=""/>
+		<set name="LINKER_DEFAULT_LIB_PATHS" value=""/>
+		<set name="LINKER_ENTRY_OPTION" value="--entry"/>
+		<set name="LINKER_GROUP_END_OPTION" value=""/>
+		<set name="LINKER_GROUP_START_OPTION" value=""/>
+		<set name="LINKER_MISC_FLAGS" value="$(LICENSERETRY_OPTION)"/>
+		<set name="LINKER_NODEBUG_OPTION" value=""/>
+		<set name="LINKER_SCRIPT_FILE_OPTION" value=""/>
+		<set name="LINKER_SYMBOLS_FILE_OPTION" value="--list"/>
+		<set name="LINKER_SYMBOLS_OPTION" value="--symbols"/> 
+		<set name="LISTING_OPTION" value="-S"/>
+		<set name="NO_EXCEPTIONS" value="--no_exceptions --no_exceptions_unwind"/>
+		<set name="NO_UNALIGNED_ACCESS" value="$(CC.NO_UNALIGNED_ACCESS)"/>
+		<set name="PREINCLUDE" value="$(RVCT_PRE_INCLUDE)"/>
+		<set name="PREINCLUDE_OPTION" value="--preinclude"/>
+		<set name="PREPROCESSOR_OPTION" value="-E"/>
+		<set name="REL_OPTIMISATION" value="-O2"/>
+		<set name="RUNTIME_SYMBOL_VISIBILITY_OPTION" value="--dllimport_runtime"/>
+		<set name="RW_BASE" value="$(RW_BASE_OPTION) 0x400000"/>
+		<set name="RW_BASE_OPTION" value="--rw-base"/> 
+		<set name="SHARED_OBJECT_OPTION" value="--dll"/>
+		<set name="SID" value=""/>
+		<set name="SO_NAME_OPTION" value="--soname"/>
+		<set name="STATIC_LIBS_PATH" value="$(RVCTLIB)/armlib"/>
+		<set name="STDCPP_INCLUDE" value="$(EPOCINCLUDE)/stdapis"/>
+		<set name="STDLIB_OPTION" value="--no_scanlib"/>	
+		<set name="SYMBIAN_LD_MESSAGE_OPTION" value="$(LD_WARNINGS_CONTROL_OPTION) $(LD_ERRORS_CONTROL_OPTION)"/>
+		<set name="SYMVER_OPTION" value="--symver_soname"/>
+		<set name="TARGET_RELOCATION_OPTION" value=""/>
+		<set name="TEMP_FILES_OPTION" value=""/>
+		<set name="THUMB_INSTRUCTION_SET" value="--thumb"/>
+		<set name="TRANASM_FLAGS" value="-n -s"/>
+		<set name="TRANASM_INPUT_OPTION" value=""/>
+		<set name="TRANASM_OUTPUT_OPTION" value="-o="/>
+		<set name="TRANSFORM_CIA" value="1"/>
+		<set name="UNDEFINED_SYMBOL_REF_OPTION" value=""/>
+		<set name="UNIX_SLASH_FOR_CC_ABS_PATHS" value="0"/>
+		<set name="UNRESOLVED_SYMBOL_REF_OPTION" value=""/>
+		<set name="USE_RVCT22_DELETE_WORKAROUND" value=""/>
+		<set name="USERINCLUDE" value=""/>
+		<set name="USER_LIBS_PATH_OPTION" value="--userlibpath"/>
+		<set name="VFE_OPTION" value="--no_vfe"/>
+		
+		<append name="CDEFS" value="__ARMCC__"/>
+	</var>
+</build>
--- a/sbsv2/raptor/lib/config/variants.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/variants.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,265 +1,268 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- Commonly used variants.
-
-	These can be referenced from the command-line or in configurations.
-	
-	-->
-  
-	<!-- This variant turns debug info on for arm only -->
-	<var name="debug_info">
-		<set name='DEBUG_INFO' value='1'/>
-	</var>
-	<!-- Run this variant to turn on trace compiler -->
-	<var name="tracecompiler">
-		<set name='USE_TRACE_COMPILER' value='1'/>
-		<env name='JAVA_HOME' default='' type='path'/>
-		<env name='SBS_JAVATC' default='$(JAVA_HOME)/bin/java.exe' type='tool' versionCommand='$(SBS_JAVATC) -version' versionResult='version \"1\.[5-9]' host='win*' />
-		<env name='SBS_JAVATC' default='$(JAVA_HOME)/bin/java' type='tool' versionCommand='$(SBS_JAVATC) -version' versionResult='version \"1\.[5-9]' host='lin*' />
-	</var>
-
-    <!-- Overrides the default debugging format for the ARM targets. -->
-    <var name="dwarf3">
-        <set name="DEBUG_FORMAT" value="$(CC.DWARF3)"/>
-    </var>
-	<var name="techview">
-	</var>
-
-	<var name="test">
-		<set name='TESTCODE' value='TRUE'/>
-	</var>
-
-	<var name="savespace">
-		<set name='SAVESPACE' value='TRUE'/>
-	</var>
-
-  <var name="generate_linkerfeedback">
-   <set name='GENERATELINKERFEEDBACK' value='TRUE'/>
-   </var>
-
-   <var name="use_linkerfeedback">
-    <set name='GENERATELINKERFEEDBACK' value='TRUE'/>
-   <set name='LINKERFEEDBACK_STAGE2' value='TRUE'/>
-   </var>
-
-   <var name="profilerfeedback">
-	   <set name='USE_PROFILER_FEEDBACK' value='TRUE'/>
-	   <env name='ARM_PROFILER_FILE' default='' type='path'/>
-   </var>
-
-   <var name="ltcg">
-	   <set name='LTCG' value='TRUE'/>
-	   <set name='LTCG_OPTION' value='--ltcg'/>
-   </var>
-
-   <var name="multifile">
-    <set name='MULTIFILE_ENABLED' value='TRUE'/>
-   </var>
-
-  <!-- build from clean can skip some processing -->
-  <var name="bfc">
-    <set name='DEPEND_SKIP' value='TRUE'/>
-  </var>
-
-	<!-- SMP variant for Kernel Code -->
-	<var name="smp">
-		<append name="CDEFS" value="__SMP__"/>
-		<append name="PLATMACROS.WINDOWS" value="SMP"/>
-		<!-- PLATMACROS.LINUX is set from PLATMACROS.WINDOWS -->
-		<append name="TRADITIONAL_PLATFORM" value='SMP' separator="" />
-		<append name="VARIANTPLATFORM" value="smp" separator=""/>
-		<set name="GENERATE_ABIV1_IMPLIBS" value=""/>
-	</var>
-
-	<!-- emit formatted releasable information into the logs for post-build parsing -->
-	<var name="whatlog">
-		<set name='WHATLOG' value='TRUE'/>
-	</var>
-
-	<var name="gcce4_3_2" extends="gcce_base">
-		<env name="GCCEBIN" type="path" />
-		<env name="GCCEVERSION" default="$(TOOLCHAINVERSION)" />
-		<set name="TOOLCHAINVERSION" value="4.3.2" />
-		<set name="OWN_LIBRARY_OPTION" value=""/>
-		<set name="STATIC_LIBS_LIST" value=""/>
-		<set name="RUNTIME_LIBS_LIST" value="drtaeabi.dso dfpaeabi.dso dfprvct3_1.dso drtrvct3_1.dso"/>
-		<set name="ARMLIBS" value=""/>
-		<set name="CC.OPT.SOFTVFP_MAYBE_VFPV2" value="-m"/>
-		<set name="CC.VAL.SOFTVFP_MAYBE_VFPV2" value="soft-float"/>
-		<set name="CC.ARMV5" value="-march=armv5t"/>
-		<set name="LD.ARMV5" value=""/>
-		<set name="LD.ARMV6" value=""/>
-		<set name="LD.ARMV7" value=""/>
-		<set name="RELOCATABLE_IMAGE_OPTION" value=""/>
-		<set name="RVCTLIB" value=""/>
-		<set name="CC.NO_UNALIGNED_ACCESS" value=""/>
-		<set name="CC.SOFTVFP_MAYBE_VFPV2" value=""/>
-		<set name="SPLIT_OPTION" value=""/>
-		<set name="NEED_ENTRYPOINT_LIBRARY" value=""/>
-		<set name="RVCTBIN" value="" />
-		<set name="RVCTINC" value="" />
-		<set name="USER_STATIC_RUNTIME_LIB" value="usrt3_1.lib"/>
-		<set name="KERNEL_STATIC_RUNTIME_LIB" value="ksrt3_1.lib"/>
-		<set name="NEED_ENTRYPOINT_LIBRARY" value="" />
-	</var>
-
-	<var name="gcce4_3_3" extends="gcce_base">
-		<env name="GCCEBIN" type="path" />
-		<env name="GCCEVERSION" default="$(TOOLCHAINVERSION)" />
-		<set name="TOOLCHAINVERSION" value="4.3.3" />
-		<set name="OWN_LIBRARY_OPTION" value=""/>
-		<set name="STATIC_LIBS_LIST" value=""/>
-		<set name="RUNTIME_LIBS_LIST" value="drtaeabi.dso dfpaeabi.dso dfprvct3_1.dso drtrvct3_1.dso"/>
-		<set name="ARMLIBS" value=""/>
-		<set name="CC.OPT.SOFTVFP_MAYBE_VFPV2" value="-m"/>
-		<set name="CC.VAL.SOFTVFP_MAYBE_VFPV2" value="soft-float"/>
-		<set name="CC.ARMV5" value="-march=armv5t"/>
-		<set name="LD.ARMV5" value=""/>
-		<set name="LD.ARMV6" value=""/>
-		<set name="LD.ARMV7" value=""/>
-		<set name="RELOCATABLE_IMAGE_OPTION" value=""/>
-		<set name="RVCTLIB" value=""/>
-		<set name="CC.NO_UNALIGNED_ACCESS" value=""/>
-		<set name="CC.SOFTVFP_MAYBE_VFPV2" value=""/>
-		<set name="SPLIT_OPTION" value=""/>
-		<set name="NEED_ENTRYPOINT_LIBRARY" value=""/>
-		<set name="RVCTBIN" value="" />
-		<set name="RVCTINC" value="" />
-		<set name="USER_STATIC_RUNTIME_LIB" value="usrt3_1.lib"/>
-		<set name="KERNEL_STATIC_RUNTIME_LIB" value="ksrt3_1.lib"/>
-		<set name="NEED_ENTRYPOINT_LIBRARY" value="" />
-	</var>
-
-	<var name="rvct2_2" extends="rvct">
-		<env name="RVCT22BIN" type="path"/>
-		<env name="RVCT22INC" type="path"/>
-		<env name="RVCT22LIB" type="path"/>
-		<set name="RVCTBIN" value="$(RVCT22BIN)"/>
-		<set name="RVCTINC" value="$(RVCT22INC)"/>
-		<set name="RVCTLIB" value="$(RVCT22LIB)"/>
-		<set name="ARMCC" value="&quot;$(RVCTBIN)/armcc$(DOTEXE)&quot;" type="tool" versionCommand="$(ARMCC) --vsn" versionResult="Compiler, RVCT2\.2\b"/>
-		<set name="OWN_LIBRARY_OPTION" value="-Ono_known_library"/>
-		<set name="RELOCATABLE_IMAGE_OPTION" value="--reloc"/>
-		<set name="SPLIT_OPTION" value="--split"/>
-		<set name="PLATMACROS.VAR" value="ARMCC_2 ARMCC_2_2"/>
-		<set name="ARMMACROS.VAR" value="__ARMCC_2__ __ARMCC_2_2__"/>
-		<set name="SYMBIAN_LINK_FLAGS.VAR" value=""/>
-		<set name="STATIC_LIBS_LIST" value="h_t__uf.l(switch8.o)"/>
-		<set name="RUNTIME_LIBS_LIST" value="drtaeabi.dso dfpaeabi.dso dfprvct2_2.dso drtrvct2_2.dso"/>
-		<set name="USER_STATIC_RUNTIME_LIB" value="usrt2_2.lib"/>
-		<set name="KERNEL_STATIC_RUNTIME_LIB" value="ksrt2_2.lib"/>
-		<set name="USRTLIB" value="usrt2_2.lib"/>
-		<set name="NEED_ENTRYPOINT_LIBRARY" value="False"/>
-		<set name="CC.NO_UNALIGNED_ACCESS" value="--memaccess -UL41"/>
-		<set name="CC.SOFTVFP_MAYBE_VFPV2" value="softvfp"/>
-		<set name="CC.ARMV5" value="--cpu 5T"/>
-		<set name="CC.ARMV6" value="--cpu 6"/>
-	</var>
-
-	<var name="rvct3_1" extends="rvct">
-		<env name="RVCT31BIN" type="path"/>
-		<env name="RVCT31INC" type="path"/>
-		<env name="RVCT31LIB" type="path"/>
-		<set name="RVCTBIN" value="$(RVCT31BIN)"/>
-		<set name="RVCTINC" value="$(RVCT31INC)"/>
-		<set name="RVCTLIB" value="$(RVCT31LIB)"/>
-		<set name="ARMCC" value="&quot;$(RVCTBIN)/armcc$(DOTEXE)&quot;" type="tool" versionCommand="$(ARMCC) --version_number" versionResult="310[6-9]\d\d\b"/>
-		<set name="OWN_LIBRARY_OPTION" value="--library_interface=aeabi_clib"/>
-		<set name="RELOCATABLE_IMAGE_OPTION" value=""/>
-		<set name="SPLIT_OPTION" value=""/>
-		<set name="PLATMACROS.VAR" value="ARMCC_3 ARMCC_3_1"/>
-		<set name="ARMMACROS.VAR" value="__ARMCC_3__ __ARMCC_3_1__"/>
-		<set name="SYMBIAN_LINK_FLAGS.VAR" value="--export_all"/>
-		<set name="STATIC_LIBS_LIST" value="h_5.l"/>
-		<set name="RUNTIME_LIBS_LIST" value="drtaeabi.dso dfpaeabi.dso dfprvct3_1.dso drtrvct3_1.dso"/>
-		<set name="USER_STATIC_RUNTIME_LIB" value="usrt3_1.lib"/>
-		<set name="KERNEL_STATIC_RUNTIME_LIB" value="ksrt3_1.lib"/>
-		<set name="USRTLIB" value="usrt3_1.lib"/>
-		<set name="NEED_ENTRYPOINT_LIBRARY" value="True"/>
-		<set name="CC.NO_UNALIGNED_ACCESS" value="--no_unaligned_access"/>
-		<set name="CC.SOFTVFP_MAYBE_VFPV2" value="softvfp"/>
-		<set name="CC.SOFTVFP_MAYBE_VFPV3" value="softvfp"/>
-		<set name="CC.ARMV5" value="--cpu=5TE"/>
-		<set name="CC.ARMV6" value="--cpu=6"/>
-		<set name="CC.ARMV7" value="--cpu=7-A"/>
-	</var>
-
-	<var name="rvct4_0" extends="rvct">
-		<env name="RVCT40BIN" type="path"/>
-		<env name="RVCT40INC" type="path"/>
-		<env name="RVCT40LIB" type="path"/>
-		<set name="RVCTBIN" value="$(RVCT40BIN)"/>
-		<set name="RVCTINC" value="$(RVCT40INC)"/>
-		<set name="RVCTLIB" value="$(RVCT40LIB)"/>
-		<set name="ARMCC" value="&quot;$(RVCTBIN)/armcc$(DOTEXE)&quot;" type="tool" versionCommand="$(ARMCC) --version_number" versionResult="400[4-9]\d\d\b"/>
-		<set name="OWN_LIBRARY_OPTION" value="--library_interface=aeabi_clib"/>
-		<set name="RELOCATABLE_IMAGE_OPTION" value=""/>
-		<set name="SPLIT_OPTION" value=""/>
-		<set name="STDLIB_OPTION" value=""/>
-		<set name="PLATMACROS.VAR" value="ARMCC_4 ARMCC_4_0"/>
-		<set name="ARMMACROS.VAR" value="__ARMCC_4__ __ARMCC_4_0__"/>
-		<set name="SYMBIAN_LINK_FLAGS.VAR" value="--override_visibility"/>
-		<set name="STATIC_LIBS_LIST" value=""/>
-		<set name="RUNTIME_LIBS_LIST" value="drtaeabi.dso dfpaeabi.dso"/>
-		<set name="USER_STATIC_RUNTIME_LIB" value="usrt4_0.lib"/>
-		<set name="KERNEL_STATIC_RUNTIME_LIB" value="ksrt4_0.lib"/>
-		<set name="USRTLIB" value="usrt4_0.lib"/>
-		<set name="NEED_ENTRYPOINT_LIBRARY" value="True"/>
-		<set name="CC.NO_UNALIGNED_ACCESS" value="--no_unaligned_access"/>
-		<set name="CC.SOFTVFP_MAYBE_VFPV2" value="softvfp+vfpv2"/>
-		<set name="CC.SOFTVFP_MAYBE_VFPV3" value="softvfp+vfpv3"/>
-		<set name="CC.ARMV5" value="--cpu=5TE"/>
-		<set name="CC.ARMV6" value="--cpu=6"/>
-		<set name="CC.ARMV7" value="--cpu=7-A"/>
-		<set name="LD.ARMV5" value="$(CC.ARMV5)"/>
-		<set name="LD.ARMV6" value="$(CC.ARMV6)"/>
-		<set name="LD.ARMV7" value="$(CC.ARMV7)"/>
-	</var>
-
-	<var name="urel">
-		<set name="DEBUG_INFO" value=""/>
-		<set name="SYMBIAN_CCFLAGS" value="$(REL_OPTIMISATION)"/>
-		<set name="VARIANTTYPE" value="urel"/>
-		<append name="CDEFS" value="NDEBUG"/>
-	</var>
-
-	<var name="udeb">
-		<set name="DEBUG_INFO" value="1"/>
-		<set name="SYMBIAN_CCFLAGS" value="$(DEBUG_OPTIMISATION)"/>
-		<set name="VARIANTTYPE" value="udeb"/>
-		<append name="CDEFS" value="_DEBUG"/>
-	</var>
-
-	<var name="remove_freeze">
-		<set name='EFREEZE_REMOVE_OPTION' value='-Remove'/>
-	</var>
-
-	<!-- OS variant mechanism is now deprecated. We retain the values for
-	     versions older than TB92sf until the mechanism is removed. -->
-
-	<!-- variant for OS version v9.4 -->
-	<var name="v94">
-		<set name='POSTLINKER_SUPPORTS_WDP' value=''/>
-		<set name='SUPPORTS_STDCPP_NEWLIB' value=''/>
-		<set name='RVCT_PRE_INCLUDE' value='$(EPOCINCLUDE)/rvct2_2/rvct2_2.h'/>
-	</var>
-
-	<!-- variants for OS version TB91* (the same as OS v9.4) -->
-	<var name="vtb91" extends="v94"/>
-	<var name="vtb91sf" extends="v94"/>
-
-	<!-- these OS variants are deliberately empty -->
-	<var name="v95"/>
-	<var name="v96"/>
-	<var name="vFuture"/>
-	<var name="vtb92"/>
-	<var name="vtb92sf"/>
-	<var name="vtb101"/>
-	<var name="vtb101sf"/>
-	
-	<!-- WINSCW specific variant for pick up nested relative include headers correctly -->
-	<var name="mwccinc">
-		<set name='OPTION_CW' value='-cwd include'/>
-	</var>
-
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- Commonly used variants.
+
+	These can be referenced from the command-line or in configurations.
+	
+	-->
+ 	
+	<!-- This variant enables building win32 tools in Linux. Tools2 on Linux only -->
+	<var name="win32">
+		<set name='TOOLS2WIN32' value='1'/>
+		<env name='SBS_MINGW_LINUX_PREFIX' default='i586-mingw32msvc'/>
+		<env name='GCC' default='$(SBS_MINGW_LINUX_PREFIX)-g++' type='tool'/>
+		<env name='ARCHIVER' default='$(SBS_MINGW_LINUX_PREFIX)-ar' type='tool'/>
+		<env name='RANLIB' default='$(SBS_MINGW_LINUX_PREFIX)-ranlib' type='tool'/>
+		<set name='RELEASEPATH' value='$(EPOCROOT)/epoc32/release/tools2/$(VARIANTTYPE)'/>
+		<set name='DOTEXE' value='.exe'/>
+		<set name='PLATMACROS.LINUX' value='$(PLATMACROS.WINDOWS)'/>
+	</var>
+
+	<!-- This variant turns debug info on for arm only -->
+	<var name="debug_info">
+		<set name='DEBUG_INFO' value='1'/>
+	</var>
+	
+	<!-- Run this variant to turn on trace compiler -->
+	<var name="tracecompiler">
+		<set name='USE_TRACE_COMPILER' value='1'/>
+		<env name='JAVA_HOME' default='' type='path'/>
+		<env name='SBS_JAVATC' default='$(JAVA_HOME)/bin/java.exe' type='tool' versionCommand='$(SBS_JAVATC) -version' versionResult='version \"1\.[5-9]' host='win*' />
+		<env name='SBS_JAVATC' default='$(JAVA_HOME)/bin/java' type='tool' versionCommand='$(SBS_JAVATC) -version' versionResult='version \"1\.[5-9]' host='lin*' />
+	</var>
+	
+	<!-- Overrides the default debugging format for the ARM targets. -->
+	<var name="dwarf3">
+		<set name="DEBUG_FORMAT" value="$(CC.DWARF3)"/>
+	</var>
+
+	<var name="techview">
+	</var>
+
+	<var name="test">
+		<set name='TESTCODE' value='TRUE'/>
+	</var>
+
+	<var name="savespace">
+		<set name='SAVESPACE' value='TRUE'/>
+	</var>
+
+	<var name="generate_linkerfeedback">
+		<set name='GENERATELINKERFEEDBACK' value='TRUE'/>
+	</var>
+
+	<var name="use_linkerfeedback">
+		<set name='GENERATELINKERFEEDBACK' value='TRUE'/>
+		<set name='LINKERFEEDBACK_STAGE2' value='TRUE'/>
+	</var>
+
+	<var name="profilerfeedback">
+		<set name='USE_PROFILER_FEEDBACK' value='TRUE'/>
+		<env name='ARM_PROFILER_FILE' default='' type='path'/>
+	</var>
+
+	<var name="ltcg">
+		<set name='LTCG' value='TRUE'/>
+		<set name='LTCG_OPTION' value='--ltcg'/>
+	</var>
+
+	<var name="multifile">
+		<set name='MULTIFILE_ENABLED' value='TRUE'/>
+	</var>
+
+	<!-- build from clean can skip some processing -->
+	<var name="bfc">
+		<set name='DEPEND_SKIP' value='TRUE'/>
+	</var>
+
+	<!-- SMP variant for Kernel Code -->
+	<var name="smp">
+		<append name="CDEFS" value="__SMP__"/>
+		<append name="PLATMACROS.WINDOWS" value="SMP"/>
+		<!-- PLATMACROS.LINUX is set from PLATMACROS.WINDOWS -->
+		<append name="TRADITIONAL_PLATFORM" value='SMP' separator="" />
+		<append name="VARIANTPLATFORM" value="smp" separator=""/>
+		<set name="SUPPORTS_ABIV1_IMPLIBS" value=""/>
+	</var>
+
+	<!-- emit formatted releasable information into the logs for post-build parsing -->
+	<var name="whatlog">
+		<set name='WHATLOG' value='TRUE'/>
+	</var>
+	
+	<var name="gcce4_3_2" extends="gcce_base">
+		<env name="SBS_GCCE432BIN" type="toolchainpath" />
+		<set name="GCCEBIN" value="$(SBS_GCCE432BIN)" />
+		<set name="GCCECC" value="$(GCCEBIN)/arm-none-symbianelf-g++$(DOTEXE)" type="tool" versionCommand="$(GCCECC) -dumpversion" versionResult="4.3.2"/>
+		<set name="RUNTIME_LIBS_LIST" value="drtaeabi.dso dfpaeabi.dso dfprvct3_1.dso drtrvct3_1.dso"/>
+		<set name="PLATMACROS.VAR" value="GCCE_4 GCCE_4_3"/>
+		<set name="ARMMACROS.VAR" value="__GCCE_4__ __GCCE_4_3__"/>
+	</var>
+
+	<var name="gcce4_3_3" extends="gcce_base">
+		<env name="SBS_GCCE433BIN" type="toolchainpath" />
+		<set name="GCCEBIN" value="$(SBS_GCCE433BIN)" />
+		<set name="GCCECC" value="$(GCCEBIN)/arm-none-symbianelf-g++$(DOTEXE)" type="tool" versionCommand="$(GCCECC) -dumpversion" versionResult="4.3.3"/>
+		<set name="RUNTIME_LIBS_LIST" value="drtaeabi.dso dfpaeabi.dso dfprvct3_1.dso drtrvct3_1.dso"/>
+		<set name="PLATMACROS.VAR" value="GCCE_4 GCCE_4_3"/>
+		<set name="ARMMACROS.VAR" value="__GCCE_4__ __GCCE_4_3__"/>
+	</var>
+	
+	<var name="gcce4_4_1" extends="gcce_base">
+		<env name="SBS_GCCE441BIN" type="toolchainpath" />
+		<set name="GCCEBIN" value="$(SBS_GCCE441BIN)" />
+		<set name="GCCECC" value="$(GCCEBIN)/arm-none-symbianelf-g++$(DOTEXE)" type="tool" versionCommand="$(GCCECC) -dumpversion" versionResult="4.4.1"/>
+		<set name="RUNTIME_LIBS_LIST" value="drtaeabi.dso dfpaeabi.dso"/>
+		<set name="PLATMACROS.VAR" value="GCCE_4 GCCE_4_4"/>
+		<set name="ARMMACROS.VAR" value="__GCCE_4__ __GCCE_4_4__"/>
+	</var>
+	
+	<var name="rvct2_2" extends="rvct">
+		<env name="RVCT22BIN" type="toolchainpath"/>
+		<env name="RVCT22INC" type="toolchainpath"/>
+		<env name="RVCT22LIB" type="toolchainpath"/>
+		<set name="RVCTBIN" value="$(RVCT22BIN)"/>
+		<set name="RVCTINC" value="$(RVCT22INC)"/>
+		<set name="RVCTLIB" value="$(RVCT22LIB)"/>
+		<set name="ARMCC" value="$(RVCTBIN)/armcc$(DOTEXE)" type="tool" versionCommand="$(ARMCC) --vsn" versionResult="Compiler, RVCT2\.2\b"/>
+		<set name="OWN_LIBRARY_OPTION" value="-Ono_known_library"/>
+		<set name="RELOCATABLE_IMAGE_OPTION" value="--reloc"/>
+		<set name="SPLIT_OPTION" value="--split"/>
+		<set name="PLATMACROS.VAR" value="ARMCC_2 ARMCC_2_2"/>
+		<set name="ARMMACROS.VAR" value="__ARMCC_2__ __ARMCC_2_2__"/>
+		<set name="SYMBIAN_LINK_FLAGS.VAR" value=""/>
+		<set name="STATIC_LIBS_LIST" value="h_t__uf.l(switch8.o)"/>
+		<set name="RUNTIME_LIBS_LIST" value="drtaeabi.dso dfpaeabi.dso dfprvct2_2.dso drtrvct2_2.dso"/>
+		<set name="USER_STATIC_RUNTIME_LIB" value="usrt2_2.lib"/>
+		<set name="USER_STATIC_RUNTIME_LIB_NESTED_EXCEPTIONS" value="usrt_nx_2_2.lib"/>
+		<set name="KERNEL_STATIC_RUNTIME_LIB" value="ksrt2_2.lib"/>
+		<set name="NEED_ENTRYPOINT_LIBRARY" value="False"/>
+		<set name="CC.NO_UNALIGNED_ACCESS" value="--memaccess -UL41"/>
+		<set name="CC.SOFTVFP_MAYBE_VFPV2" value="softvfp"/>
+		<set name="PL.SOFTVFP_MAYBE_VFPV2" value="softvfp"/>
+		<set name="CC.ARMV5" value="--cpu 5T"/>
+		<set name="CC.ARMV6" value="--cpu 6"/>
+		<set name="USE_RVCT22_DELETE_WORKAROUND" value="1" />
+	</var>
+
+	<var name="rvct3_1" extends="rvct">
+		<env name="RVCT31BIN" type="toolchainpath"/>
+		<env name="RVCT31INC" type="toolchainpath"/>
+		<env name="RVCT31LIB" type="toolchainpath"/>
+		<set name="RVCTBIN" value="$(RVCT31BIN)"/>
+		<set name="RVCTINC" value="$(RVCT31INC)"/>
+		<set name="RVCTLIB" value="$(RVCT31LIB)"/>
+		<set name="ARMCC" value="$(RVCTBIN)/armcc$(DOTEXE)" type="tool" versionCommand="$(ARMCC) --version_number" versionResult="310[6-9]\d\d\b"/>
+		<set name="OWN_LIBRARY_OPTION" value="--library_interface=aeabi_clib"/>
+		<set name="RELOCATABLE_IMAGE_OPTION" value=""/>
+		<set name="SPLIT_OPTION" value=""/>
+		<set name="PLATMACROS.VAR" value="ARMCC_3 ARMCC_3_1"/>
+		<set name="ARMMACROS.VAR" value="__ARMCC_3__ __ARMCC_3_1__"/>
+		<set name="SYMBIAN_LINK_FLAGS.VAR" value="--export_all"/>
+		<set name="STATIC_LIBS_LIST" value="h_5.l"/>
+		<set name="RUNTIME_LIBS_LIST" value="drtaeabi.dso dfpaeabi.dso dfprvct3_1.dso drtrvct3_1.dso"/>
+		<set name="USER_STATIC_RUNTIME_LIB" value="usrt3_1.lib"/>
+		<set name="USER_STATIC_RUNTIME_LIB_NESTED_EXCEPTIONS" value="usrt_nx_3_1.lib"/>
+		<set name="KERNEL_STATIC_RUNTIME_LIB" value="ksrt3_1.lib"/>
+		<set name="NEED_ENTRYPOINT_LIBRARY" value="True"/>
+		<set name="CC.NO_UNALIGNED_ACCESS" value="--no_unaligned_access"/>
+		<set name="CC.SOFTVFP_MAYBE_VFPV2" value="softvfp"/>
+		<set name="PL.SOFTVFP_MAYBE_VFPV2" value="softvfp"/>
+		<set name="CC.SOFTVFP_MAYBE_VFPV3" value="softvfp"/>
+		<set name="PL.SOFTVFP_MAYBE_VFPV3" value="softvfp"/>
+		<set name="CC.ARMV5" value="--cpu 5TE"/>
+		<set name="CC.ARMV6" value="--cpu 6"/>
+		<set name="CC.ARMV7" value="--cpu 7-A"/>
+	</var>
+
+	<var name="rvct4_0" extends="rvct">
+		<env name="RVCT40BIN" type="toolchainpath"/>
+		<env name="RVCT40INC" type="toolchainpath"/>
+		<env name="RVCT40LIB" type="toolchainpath"/>
+		<set name="RVCTBIN" value="$(RVCT40BIN)"/>
+		<set name="RVCTINC" value="$(RVCT40INC)"/>
+		<set name="RVCTLIB" value="$(RVCT40LIB)"/>
+		<set name="ARMCC" value="$(RVCTBIN)/armcc$(DOTEXE)" type="tool" versionCommand="$(ARMCC) --version_number" versionResult="400[4-9]\d\d\b"/>
+		<set name="OWN_LIBRARY_OPTION" value="--library_interface=aeabi_clib"/>
+		<set name="RELOCATABLE_IMAGE_OPTION" value=""/>
+		<set name="SPLIT_OPTION" value=""/>
+		<set name="PLATMACROS.VAR" value="ARMCC_4 ARMCC_4_0"/>
+		<set name="ARMMACROS.VAR" value="__ARMCC_4__ __ARMCC_4_0__"/>
+		<set name="SYMBIAN_LINK_FLAGS.VAR" value="--override_visibility"/>
+		<set name="STATIC_LIBS_LIST" value=""/>
+		<set name="RUNTIME_LIBS_LIST" value="drtaeabi.dso dfpaeabi.dso"/>
+		<set name="USER_STATIC_RUNTIME_LIB" value="usrt4_0.lib"/>
+		<set name="USER_STATIC_RUNTIME_LIB_NESTED_EXCEPTIONS" value="usrt_nx_4_0.lib"/>
+		<set name="KERNEL_STATIC_RUNTIME_LIB" value="ksrt4_0.lib"/>
+		<set name="NEED_ENTRYPOINT_LIBRARY" value="True"/>
+		<set name="CC.NO_UNALIGNED_ACCESS" value="--no_unaligned_access"/>
+		<set name="CC.SOFTVFP_MAYBE_VFPV2" value="softvfp+vfpv2"/>
+		<set name="PL.SOFTVFP_MAYBE_VFPV2" value="vfpv2"/>
+		<set name="CC.SOFTVFP_MAYBE_VFPV3" value="softvfp+vfpv3"/>
+		<!-- Not supported yet : <set name="PL.SOFTVFP_MAYBE_VFPV3" value="vfpv3"/> -->
+		<set name="PL.SOFTVFP_MAYBE_VFPV3" value="vfpv2"/>
+		<set name="CC.ARMV5" value="--cpu 5TE"/>
+		<set name="CC.ARMV6" value="--cpu 6"/>
+		<set name="CC.ARMV7" value="--cpu 7-A"/>
+	</var>
+
+	<var name="urel">
+		<set name="DEBUG_INFO" value=""/>
+		<set name="SYMBIAN_CCFLAGS" value="$(REL_OPTIMISATION)"/>
+		<set name="VARIANTTYPE" value="urel"/>
+		<append name="CDEFS" value="NDEBUG"/>
+	</var>
+
+	<var name="udeb">
+		<set name="DEBUG_INFO" value="1"/>
+		<set name="SYMBIAN_CCFLAGS" value="$(DEBUG_OPTIMISATION)"/>
+		<set name="VARIANTTYPE" value="udeb"/>
+		<append name="CDEFS" value="_DEBUG"/>
+	</var>
+
+	<var name="remove_freeze">
+		<set name='EFREEZE_REMOVE_OPTION' value='-Remove'/>
+	</var>
+
+	<!-- OS variant mechanism is now deprecated. We retain the values for
+	     versions older than TB92sf until the mechanism is removed. -->
+
+	<!-- variant for OS version v9.4 -->
+	<var name="v94">
+		<set name='POSTLINKER_SUPPORTS_WDP' value=''/>
+		<set name='SUPPORTS_STDCPP_NEWLIB' value=''/>
+		<set name='RVCT_PRE_INCLUDE' value='$(EPOCINCLUDE)/rvct2_2/rvct2_2.h'/>
+	</var>
+
+	<!-- variants for OS version TB91* (the same as OS v9.4) -->
+	<var name="vtb91" extends="v94"/>
+	<var name="vtb91sf" extends="v94"/>
+
+	<!-- these OS variants are deliberately empty -->
+	<var name="v95"/>
+	<var name="v96"/>
+	<var name="vFuture"/>
+	<var name="vtb92"/>
+	<var name="vtb92sf"/>
+	<var name="vtb101"/>
+	<var name="vtb101sf"/>
+	
+	<!-- WINSCW specific variant for pick up nested relative include headers correctly -->
+	<var name="mwccinc">
+		<set name='OPTION_CW' value='-cwd include'/>
+	</var>
+	
+	<!-- Variant to allow GCCE-built binaries to be created in epoc32/release/gcce, 
+	     epoc32/release/gccev6 and epoc32/release/gccev7 -->
+	<var name="release_gcce">
+		<set name="VARIANTPLATFORM" value="gcce" />
+		<set name="STATIC_RUNTIME_DIR" value="$(EPOCROOT)/epoc32/release/armv5/$(VARIANTTYPE)"/>
+		<set name="STATIC_LIBRARY_DIR" value="$(EPOCROOT)/epoc32/release/armv5/$(VARIANTTYPE)"/>
+	</var>
+	<var name="release_gccev6" extends="release_gcce" >
+		<set name="VARIANTPLATFORM" value="gccev6" />
+	</var>
+	<var name="release_gccev7" extends="release_gcce" >
+		<set name="VARIANTPLATFORM" value="gccev7" />
+	</var>
+</build>
--- a/sbsv2/raptor/lib/config/winscw.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/config/winscw.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,143 +1,153 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- build configurations for Metrowerks Emulator compilers -->
-	<var name="winscw_base" extends="root">
-		<varRef ref="default.interfaces"/>
-		<varRef ref="default.locations"/>
-		<!-- picked up from the Environment -->
-		<env name='CHECKLIB' default='$(EPOCROOT)/epoc32/tools/checklib$(DOTEXE)' type='tool'/>
-		<env name='EFREEZE' default="$(PERL) $(EPOCROOT)/epoc32/tools/efreeze.pl" type='tool'/>
-		<env name='BMCONV' default="$(EPOCROOT)/epoc32/tools/bmconv$(DOTEXE)" type='tool'/>
-		<env name='MAKEDEF' default='$(PERL) $(EPOCROOT)/epoc32/tools/makedef.pl' type='path'/>
-		<env name='MWCC' default='mwccsym2$(DOTEXE)' type='tool' versionCommand='$(MWCC) -version' versionResult='Version 3.2.*'/>
-		<env name='MWLD' default='mwldsym2$(DOTEXE)' type='tool' versionCommand='$(MWLD) -version' versionResult='Version 3.2.*'/>
-		<env name='MWWINRC' default='mwwinrc$(DOTEXE)' type='tool' versionCommand='$(MWWINRC) -version' versionResult='Version 3.2.*'/>
-
-		<env name='PREPDEF' default='$(PERL) $(EPOCROOT)/epoc32/tools/prepdef.pl' type='path'/>
-		<env name='RCOMP' default='$(EPOCROOT)/epoc32/tools/rcomp$(DOTEXE)' type='tool'/>
-		<env name='STRINGTABLE' default='$(PERL) $(EPOCROOT)/epoc32/tools/stringtable.pl' type='path'/>	
-		
-		<!-- link to bld.inf and mmp platform names -->
-		<set name='TRADITIONAL_PLATFORM' value='WINSCW'/>
-
-		<!-- interfaces -->
-		<set name="INTERFACE.ani" value="Emulator.ani"/>
-		<set name="INTERFACE.bitmap" value="Emulator.bitmap"/>
-		<set name="INTERFACE.exe" value="Emulator.exe"/>
-		<set name="INTERFACE.stdexe" value="Emulator.stdexe"/>
-		<set name="INTERFACE.dll" value="Emulator.dll"/>
-		<set name="INTERFACE.stddll" value="Emulator.stddll"/>
-		<set name="INTERFACE.exexp" value="Emulator.exexp"/>
-		<set name="INTERFACE.fsy" value="Emulator.fsy"/>
-		<set name="INTERFACE.implib" value="Emulator.implib"/>
-		<set name="INTERFACE.kdll" value="Emulator.kdll"/>
-		<set name="INTERFACE.kext" value="Emulator.kext"/>
-		<set name="INTERFACE.klib" value="Emulator.klib"/>
-		<set name="INTERFACE.ldd" value="Emulator.ldd"/>
-		<set name="INTERFACE.lib" value="Emulator.lib"/>
-		<set name="INTERFACE.stdlib" value="Emulator.stdlib"/>
-		<set name="INTERFACE.none" value="Emulator.none"/>
-		<set name="INTERFACE.pdd" value="Emulator.pdd"/>
-		<set name="INTERFACE.pdl" value="Emulator.pdl"/>
-		<set name="INTERFACE.plugin" value="Emulator.plugin"/>
-		<set name="INTERFACE.resource" value="Emulator.resource"/>
-		<set name="INTERFACE.textnotifier2" value="Emulator.textnotifier2"/>
-		<set name="INTERFACE.var" value="Emulator.var"/>
-		<set name='CC' value='$(MWCC)'/>
-		<set name='CDEFS' value='__SYMBIAN32__ __CW32__ __WINS__ __WINSCW__ __SUPPORT_CPP_EXCEPTIONS__ _UNICODE $(MMPDEFS)'/>
-		<set name='CFLAGS' value='-c -align 4 -warnings on -w nohidevirtual,nounusedexpr -msgstyle gcc -enum int -str pool -exc ms -trigraphs on -cwd source'/>
-		<set name='CW_DEFAULT_LIBS' value='gdi32.lib user32.lib kernel32.lib'/>
-		<set name='CW_RUNTIME_STATIC' value='msl_all_static_mse_symbian_d.lib'/>
-		<set name='CW_RUNTIME_NONSTATIC' value='MSL_All_x86_Symbian_D.lib'/>
-		<set name='DEFAULT_NORMAL_NEWLIB' value='scppnwdl.lib'/>
-		<set name='DEFAULT_SYSTEM_NEWLIB' value='scppnwdl_kern.lib'/>
-		<set name='EXPORT_TYPE' value='dllexport'/>
-		<set name='LD' value='$(MWLD)'/>
-		<set name='LFLAGS' value='-msgstyle gcc -stdlib -subsystem windows'/>
-		<set name='LFLAGS_INFGEN' value='-S -show only,names,unmangled,verbose '/>
-		<set name='LFLAGS_SYMGEN' value='-S -show only,names,verbose '/>
-		<set name='LINKPATH' value='winscw/udeb'/>
-		<set name='LISTING_OPTION' value='-S'/>
-		<set name='MMPDEFS' value=''/>
-		<set name='EPOCSTACKSIZE' value=''/>
-		<set name='NMAKE' value='nmake'/>
-		<set name='NMAKEFLAGS' value='-nologo -x - '/>
-		<set name='OPT.ADDCOMMAND' value='-addcommand '/>
-		<set name='OPT.CHECKLIB.STDCPP' value='stdc++'/>
-		<set name='OPT.CHECKLIB.SYMCPP' value='symc++'/>
-		<set name='OPT.CHECKLIB.WIN32' value='--coff'/>
-		<set name='OPT.HEAPCOMMIT' value='-heapcommit='/>
-		<set name='OPT.DEFINE' value='-d '/>
-		<set name='OPT.DEFFILE' value='-f '/>
-		<set name='OPT.DEPEND' value='-gccdepends -MD '/>
-		<set name='OPT.EXPORT' value='-export '/>
-		<set name='OPT.HEAPRESERVE' value='-heapreserve='/>
-		<set name='OPT.IMAGEBASE' value='-imagebase '/>
-		<set name='OPT.IMPLIB' value='-implib '/>
-		<set name='OPT.IMPORTLIB' value='-importlib '/>
-		<set name='OPT.LIBFILE' value='-l'/>
-		<set name='OPT.LIBPATH' value='-l '/>
-		<set name='OPT.LISTING' value='-S -show source,unmangled,comments '/>
-		<set name='OPT.MENTRYPOINT' value='-m '/>
-		<set name='OPT.MAINENTRYPOINT' value='-main '/>
-		<set name='OPT.MAP' value='-map '/>
-		<set name='OPT.NOCOMPACTIMPORTLIB' value='-nocompactimportlib '/>
-		<set name='OPT.NOENTRY' value='-noentry '/>
-		<set name='OPT.NOIMPLIB' value='-noimplib '/>
-		<set name='OPT.NOSTDINC' value='-nostdinc '/>
-		<set name='OPT.OUT' value='-o '/>
-		<set name='OPT.PREINCLUDE' value='-include '/>
-		<set name='OPT.RUNTIME' value='-runtime '/>
-		<set name='OPT.SEARCH' value='-search'/>
-		<set name='OPT.SHARED' value='-shared '/>
-		<set name='OPT.SPLITINCLUDE' value='-i-'/>
-		<set name='OPT.STATICLIBRARY' value='-library '/>
-		<set name='OPT.STDINC' value='-stdinc '/>
-		<set name='OPT.STDLIB' value='-stdlib '/>
-		<set name='OPT.SYM' value='-sym '/>
-		<set name='OPT.SYSINCLUDE' value='-i '/>
-		<set name='OPT.USERINCLUDE' value='-i '/>
-		<set name='OPT.WCHAR' value='-wchar_t '/>
-		<set name='OPT.WARNINGS' value='-warnings '/>
-		<set name='OUTPUTPATH' value='$(SBS_BUILD_DIR)'/>
-		<set name='BLDINF_OUTPUTPATH' value='$(SBS_BUILD_DIR)'/>
-		<set name='RC' value='$(MWWINRC)'/>
-		<set name='RELEASEPATH' value='$(EPOCROOT)/epoc32/release'/>
-		<set name='SBSV1MAKE' value='$(EPOCROOT)/epoc32/tools/make$(DOTEXE)'/>
-		<set name='STDCPP_DEF' value='__SYMBIAN_STDCPP_SUPPORT__'/>
-		<set name='STDCPP_INCLUDE' value='$(EPOCINCLUDE)/stdapis'/>
-		<set name='STDCPP_WCHAR_DEF' value='__wchar_t_defined'/>
-		<set name='SYMLOOKUPUTIL' value='$(PERL) $(EPOCROOT)/epoc32/tools/sym_lkup_util.pl'/>
-		<set name='SYMLOOKUPARGS' value='--ignore_export_dir'/>
-		<set name='SYSTEMINCLUDE' value=''/>
-		<set name='TARGET' value='TARGET_WAS_NOT_SET_PROPERLY'/>
-		<set name='TARGETPATH' value=''/>
-		<set name='TARGETTYPE' value='TARGETTYPE_WAS_NOT_SET_PROPERLY'/>
-		<set name='USERINCLUDE' value=''/>
-		<set name='VARIANTPLATFORM' value='winscw'/>
-		<set name='PLATMACROS.WINDOWS' value='CW32 WINS WINSCW'/>
-		<set name='PLATMACROS.LINUX' value='$(PLATMACROS.WINDOWS)'/>
-	</var>
-
-	<var name="winscw_udeb" extends="winscw_base">
-		<set name='FULLVARIANTPATH' value='winscw/udeb'/>
-		<set name='VARIANTTYPE' value='udeb'/>
-
-		<append name='CDEFS' value='_DEBUG'/>
-		<append name='CFLAGS' value='-g -O0 -inline off'/>
-		<append name='LFLAGS' value='-g'/>
-	</var>
-
-	<var name="winscw_urel" extends="winscw_base">
-		<set name='FULLVARIANTPATH' value='winscw/urel'/>
-		<set name='VARIANTTYPE' value='urel'/>
-
-		<append name='CDEFS' value='NDEBUG'/>
-		<append name='CFLAGS' value='-O4,s'/>
-	</var>
-
-	<group name="winscw">
-		<varRef ref="winscw_urel"/>
-		<varRef ref="winscw_udeb"/>
-	</group>
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- build variants for CodeWarrior toolchains -->
+	<var name="winscw_base" extends="root">
+		<varRef ref="default.interfaces"/>
+		<varRef ref="default.locations"/>
+		
+		<!-- toolchain tools -->
+		<env name="MWCC" default="mwccsym2$(DOTEXE)" type="tool" versionCommand="$(MWCC) -version" versionResult="Version 3.2.*"/>
+		<env name="MWLD" default="mwldsym2$(DOTEXE)" type="tool" versionCommand="$(MWLD) -version" versionResult="Version 3.2.*"/>
+		<env name="MWWINRC" default="mwwinrc$(DOTEXE)" type="tool" versionCommand="$(MWWINRC) -version" versionResult="Version 3.2.*"/>
+		
+		<set name="CC" value="$(MWCC)"/>
+		<set name="LD" value="$(MWLD)"/>
+		<set name="RC" value="$(MWWINRC)"/>
+		
+		<!-- tools and scripts -->
+		<env name="BMCONV" default="$(EPOCROOT)/epoc32/tools/bmconv$(DOTEXE)" type="tool"/>
+		<env name="CHECKLIB" default="$(EPOCROOT)/epoc32/tools/checklib$(DOTEXE)" type="tool"/>
+		<env name="EFREEZE" default="$(PERL) $(EPOCROOT)/epoc32/tools/efreeze.pl" type="script"/>
+		<env name="MAKEDEF" default="$(PERL) $(EPOCROOT)/epoc32/tools/makedef.pl" type="script"/>
+		<env name="PREPDEF" default="$(PERL) $(EPOCROOT)/epoc32/tools/prepdef.pl" type="script"/>
+		<env name="RCOMP" default="$(EPOCROOT)/epoc32/tools/rcomp$(DOTEXE)" type="tool"/>
+		<env name="SBSV1MAKE" default="$(EPOCROOT)/epoc32/tools/make$(DOTEXE)" type="tool"/>
+		<env name="STRINGTABLE" default="$(PERL) $(EPOCROOT)/epoc32/tools/stringtable.pl" type="script"/>	
+		
+		<!-- link to bld.inf and mmp platform names -->
+		<set name="TRADITIONAL_PLATFORM" value="WINSCW"/>
+
+		<!-- interfaces -->
+		<set name="INTERFACE.ani" value="Emulator.ani"/>
+		<set name="INTERFACE.bitmap" value="Emulator.bitmap"/>
+		<set name="INTERFACE.exe" value="Emulator.exe"/>
+		<set name="INTERFACE.stdexe" value="Emulator.stdexe"/>
+		<set name="INTERFACE.dll" value="Emulator.dll"/>
+		<set name="INTERFACE.pdll" value="Emulator.pdll"/>
+		<set name="INTERFACE.stddll" value="Emulator.stddll"/>
+		<set name="INTERFACE.exexp" value="Emulator.exexp"/>
+		<set name="INTERFACE.fsy" value="Emulator.fsy"/>
+		<set name="INTERFACE.implib" value="Emulator.implib"/>
+		<set name="INTERFACE.kdll" value="Emulator.kdll"/>
+		<set name="INTERFACE.kext" value="Emulator.kext"/>
+		<set name="INTERFACE.klib" value="Emulator.klib"/>
+		<set name="INTERFACE.ldd" value="Emulator.ldd"/>
+		<set name="INTERFACE.lib" value="Emulator.lib"/>
+		<set name="INTERFACE.stdlib" value="Emulator.stdlib"/>
+		<set name="INTERFACE.none" value="Emulator.none"/>
+		<set name="INTERFACE.pdd" value="Emulator.pdd"/>
+		<set name="INTERFACE.pdl" value="Emulator.pdl"/>
+		<set name="INTERFACE.plugin" value="Emulator.plugin"/>
+		<set name="INTERFACE.plugin3" value="Emulator.plugin3"/>
+		<set name="INTERFACE.resource" value="Emulator.resource"/>
+		<set name="INTERFACE.textnotifier2" value="Emulator.textnotifier2"/>
+		<set name="INTERFACE.var" value="Emulator.var"/>
+		
+		<set name="BLDINF_OUTPUTPATH" value="$(SBS_BUILD_DIR)"/>
+		<set name="CDEFS" value="__SYMBIAN32__ __CW32__ __WINS__ __WINSCW__ __SUPPORT_CPP_EXCEPTIONS__ _UNICODE $(MMPDEFS)"/>
+		<set name="CFLAGS" value="-c -align 4 -warnings on -w nohidevirtual,nounusedexpr -msgstyle gcc -enum int -str pool -exc ms -trigraphs on -cwd source"/>
+		<set name="CW_DEFAULT_LIBS" value="gdi32.lib user32.lib kernel32.lib"/>
+		<set name="CW_RUNTIME_NONSTATIC" value="MSL_All_x86_Symbian_D.lib"/>
+		<set name="CW_RUNTIME_STATIC" value="msl_all_static_mse_symbian_d.lib"/>
+		<set name="DEFAULT_NORMAL_NEWLIB" value="scppnwdl.lib"/>
+		<set name="DEFAULT_SYSTEM_NEWLIB" value="scppnwdl_kern.lib"/>
+		<set name="EPOCSTACKSIZE" value=""/>
+		<set name="EXPORT_TYPE" value="dllexport"/>
+		<set name="LFLAGS" value="-msgstyle gcc -stdlib -subsystem windows"/>
+		<set name="LFLAGS_INFGEN" value="-S -show only,names,unmangled,verbose "/>
+		<set name="LFLAGS_SYMGEN" value="-S -show only,names,verbose "/>
+		<set name="LINKPATH" value="winscw/udeb"/>
+		<set name="LISTING_OPTION" value="-S"/>
+		<set name="MMPDEFS" value=""/>
+		<set name="NMAKE" value="nmake"/>
+		<set name="NMAKEFLAGS" value="-nologo -x - "/>
+		<set name="OPT.ADDCOMMAND" value="-addcommand "/>
+		<set name="OPT.CHECKLIB.STDCPP" value="stdc++"/>
+		<set name="OPT.CHECKLIB.SYMCPP" value="symc++"/>
+		<set name="OPT.CHECKLIB.WIN32" value="--coff"/>
+		<set name="OPT.DEFFILE" value="-f "/>
+		<set name="OPT.DEFINE" value="-d "/>
+		<set name="OPT.DEPEND" value="-gccdepends -MD "/>
+		<set name="OPT.EXPORT" value="-export "/>
+		<set name="OPT.HEAPCOMMIT" value="-heapcommit="/>
+		<set name="OPT.HEAPRESERVE" value="-heapreserve="/>
+		<set name="OPT.IMAGEBASE" value="-imagebase "/>
+		<set name="OPT.IMPLIB" value="-implib "/>
+		<set name="OPT.IMPORTLIB" value="-importlib "/>
+		<set name="OPT.LIBFILE" value="-l"/>
+		<set name="OPT.LIBPATH" value="-l "/>
+		<set name="OPT.LISTING" value="-S -show source,unmangled,comments "/>
+		<set name="OPT.MAINENTRYPOINT" value="-main "/>
+		<set name="OPT.MAP" value="-map "/>
+		<set name="OPT.MENTRYPOINT" value="-m "/>
+		<set name="OPT.NOCOMPACTIMPORTLIB" value="-nocompactimportlib "/>
+		<set name="OPT.NOENTRY" value="-noentry "/>
+		<set name="OPT.NOIMPLIB" value="-noimplib "/>
+		<set name="OPT.NOSTDINC" value="-nostdinc "/>
+		<set name="OPT.OUT" value="-o "/>
+		<set name="OPT.PREINCLUDE" value="-include "/>
+		<set name="OPT.RUNTIME" value="-runtime "/>
+		<set name="OPT.SEARCH" value="-search"/>
+		<set name="OPT.SHARED" value="-shared "/>
+		<set name="OPT.SPLITINCLUDE" value="-i-"/>
+		<set name="OPT.STATICLIBRARY" value="-library "/>
+		<set name="OPT.STDINC" value="-stdinc "/>
+		<set name="OPT.STDLIB" value="-stdlib "/>
+		<set name="OPT.SYM" value="-sym "/>
+		<set name="OPT.SYSINCLUDE" value="-i "/>
+		<set name="OPT.USERINCLUDE" value="-i "/>
+		<set name="OPT.WARNINGS" value="-warnings "/>
+		<set name="OPT.WCHAR" value="-wchar_t "/>
+		<set name="OUTPUTPATH" value="$(SBS_BUILD_DIR)"/>
+		<set name="RELEASEPATH" value="$(EPOCROOT)/epoc32/release"/>
+		<set name="STDCPP_DEF" value="__SYMBIAN_STDCPP_SUPPORT__"/>
+		<set name="STDCPP_INCLUDE" value="$(EPOCINCLUDE)/stdapis"/>
+		<set name="STDCPP_WCHAR_DEF" value="__wchar_t_defined"/>
+		<set name="SYMLOOKUPARGS" value="--ignore_export_dir"/>
+		<set name="SYMLOOKUPUTIL" value="$(PERL) $(EPOCROOT)/epoc32/tools/sym_lkup_util.pl"/>
+		<set name="SYSTEMINCLUDE" value=""/>
+		<set name="TARGET" value="TARGET_WAS_NOT_SET_PROPERLY"/>
+		<set name="TARGETPATH" value=""/>
+		<set name="TARGETTYPE" value="TARGETTYPE_WAS_NOT_SET_PROPERLY"/>
+		<set name="USERINCLUDE" value=""/>
+		<set name="VARIANTPLATFORM" value="winscw"/>
+		
+		<!-- macros -->
+		<set name="PLATMACROS.WINDOWS" value="CW32 WINS WINSCW"/>
+		<set name="PLATMACROS.LINUX" value="$(PLATMACROS.WINDOWS)"/>
+	</var>
+
+	<var name="winscw_debug">
+		<set name="FULLVARIANTPATH" value="winscw/udeb"/>
+		<set name="VARIANTTYPE" value="udeb"/>
+
+		<append name="CDEFS" value="_DEBUG"/>
+		<append name="CFLAGS" value="-g -O0 -inline off"/>
+		<append name="LFLAGS" value="-g"/>
+	</var>
+	<alias name="winscw_udeb" meaning="winscw_base.winscw_debug"/>
+	
+	<var name="winscw_release">
+		<set name="FULLVARIANTPATH" value="winscw/urel"/>
+		<set name="VARIANTTYPE" value="urel"/>
+
+		<append name="CDEFS" value="NDEBUG"/>
+		<append name="CFLAGS" value="-O4,s"/>
+	</var>
+	<alias name="winscw_urel" meaning="winscw_base.winscw_release"/>
+	
+	<group name="winscw">
+		<aliasRef ref="winscw_urel"/>
+		<aliasRef ref="winscw_udeb"/>
+	</group>
+</build>
--- a/sbsv2/raptor/lib/flm/analysis.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/analysis.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,199 +1,199 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- analysis interfaces -->
-
-	<interface name="analysis.flm" extends="base.flm" abstract="true">
-
-		<!-- analysis specific -->
-
-		<param name='EXPORTHEADERS' default=''/>
-		<param name='RESOURCEFILES' default=''/>
-
-		<!-- generic -->
-
-		<param name='NMAKE'/>
-		<param name='NMAKEFLAGS'/>
-		<param name='OUTPUTPATH'/>
-		<param name='PRODUCT_INCLUDE'/>
-		<param name='RELEASEPATH'/>
-		<param name='REQUESTEDTARGETEXT' default=''/>
-		<param name='SBSV1MAKE'/>
-		<param name='VARIANTTYPE'/>
-		<param name='FULLVARIANTPATH'/>
-		<param name='SUPPORTS_STDCPP_NEWLIB' default='1'/>
-	</interface>
-
-	<interface name="analysis.mmp" extends="analysis.flm" abstract="true">
-		<param name='CAPABILITY' default='none'/>
-		<param name='DEFFILE' default=''/>
-		<param name='FIRSTLIB' default=''/>
-		<param name='KERNEL_MODE_DEF'/>
-		<param name='KERNEL_MODE_INCLUDES'/>			
-		<param name='LIBRARY' default=''/>
-		<param name='LINKAS' default=''/>
-		<param name='MMPDEFS' default=''/>
-		<param name='NOSTDCPP' default=''/>
-		<param name='OPEN_ENVIRONMENT' default=''/>
-		<param name='SOURCE' default=''/>
-		<param name='STATICLIBRARY' default=''/>
-		<param name='STDCPP' default=''/>
-		<param name='STDCPP_DEF'/>
-		<param name='STDCPP_INCLUDE'/>
-		<param name='SYSTEMINCLUDE' default=''/>
-		<param name='TARGET'/>
-		<param name='TARGETPATH' default=''/>
-		<param name='TARGETTYPE'/>
-		<param name='TARGET_DEFS' default=''/>
-		<param name='TARGET_INCLUDES' default=''/>
-		<param name='UID2' default='00000000'/>
-		<param name='UID2_ZERO_OVERRIDE' default=''/>
-		<param name='UID3' default='00000000'/>
-		<param name='USERINCLUDE' default=''/>
-		<param name='VERSION' default='1.0'/>
-		<param name='OPTION_GCCXML' default=''/>
-		<param name='VERSIONHEX' default='00010000'/>
-	</interface>
-
-	<interface name="analysis.all" extends="analysis.mmp" abstract="true" flm="gccxml.flm">
-		<param name='CC'/>
-		<param name='CDEFS'/>
-		<param name='CFLAGS'/>
-		<param name='CPPFLAGS'/>
-		<param name='CREATERFIFILE'/>
-		<param name='GNUCPP'/>
-		<param name='GNUSED'/>
-		<param name='GNUAWK'/>
-		<param name='OPT.DEFINE'/>
-		<param name='OPT.OUT'/>
-		<param name='OPT.PREINCLUDE'/>
-		<param name='OPT.SPLITINCLUDE'/>
-		<param name='OPT.SYSINCLUDE'/>
-		<param name='OPT.USERINCLUDE'/>
-		<param name='ZIP'/>
-	</interface>
-
-	<!-- basic types -->
-
-	<interface name="analysis.exe" extends="analysis.all">
-		<param name='FIRSTLIB' default="eexe.lib"/>
-		<param name='UID1' default="1000007a"/>
-	</interface>
-
-	<interface name="analysis.dll" extends="analysis.all">
-		<param name='FIRSTLIB' default="edll.lib"/>
-		<param name='UID1' default="10000079"/>
-	</interface>
-
-	<interface name="analysis.lib" extends="analysis.all">
-		<param name='FIRSTLIB' default="elib.lib"/>
-		<param name='UID1' default="00000000"/>
-	</interface>
-
-	<!-- variations on the basic types -->
-
-	<interface name="analysis.ani" extends="analysis.dll">
-		<param name='UID2' default="10003b22"/>
-	</interface>
-
-	<interface name="analysis.exexp" extends="analysis.exe">
-	</interface>
-
-	<interface name="analysis.fsy" extends="analysis.dll">
-		<param name='UID2_ZERO_OVERRIDE' default="100039df"/>
-	</interface>
-
-	<interface name="analysis.kdll" extends="analysis.dll">
-		<param name='TARGET_DEFS' default='$(KERNEL_MODE_DEF)'/>
-		<param name='TARGET_INCLUDES' default='$(KERNEL_MODE_INCLUDES)'/>		
-		<param name='FIRSTLIB' default="ekll.lib"/>
-	</interface>
-
-	<interface name="analysis.kext" extends="analysis.dll">
-		<param name='TARGET_DEFS' default='$(KERNEL_MODE_DEF)'/>
-		<param name='TARGET_INCLUDES' default='$(KERNEL_MODE_INCLUDES)'/>	
-		<param name='FIRSTLIB' default="eext.lib"/>
-	</interface>
-
-	<interface name="analysis.klib" extends="analysis.lib">
-		<param name='TARGET_DEFS' default='$(KERNEL_MODE_DEF)'/>
-	</interface>
-
-	<interface name="analysis.ldd" extends="analysis.dll">
-		<param name='TARGET_DEFS' default='$(KERNEL_MODE_DEF)'/>
-		<param name='TARGET_INCLUDES' default='$(KERNEL_MODE_INCLUDES)'/>	
-		<param name='FIRSTLIB' default="edev.lib"/>
-		<param name='UID2_ZERO_OVERRIDE' default="100000af"/>
-	</interface>
-
-	<interface name="analysis.pdd" extends="analysis.dll">
-		<param name='TARGET_DEFS' default='$(KERNEL_MODE_DEF)'/>
-		<param name='TARGET_INCLUDES' default='$(KERNEL_MODE_INCLUDES)'/>	
-		<param name='FIRSTLIB' default="edev.lib"/>
-		<param name='UID2_ZERO_OVERRIDE' default="100039d0"/>
-	</interface>
-
-	<interface name="analysis.pdl" extends="analysis.dll">
-		<param name='UID2' default="10003b1c"/>
-	</interface>
-
-	<interface name="analysis.plugin" extends="analysis.dll">
-		<param name='UID2' default="10009D8D"/>
-	</interface>
-
-	<interface name="analysis.resource" extends="base.resource" flm="gccxmlresource.flm">
-		<param name='CREATERFIFILE'/>
-		<param name='OUTPUTPATHOFFSET' default=''/>
-		<param name='MAIN_OUTPUTPATH' default=''/>
-		<param name='MAIN_TARGET_lower' default=''/>
-		<param name='MAIN_REQUESTEDTARGETEXT' default=''/>
-		<param name='RFIFILE' default=''/>
-	</interface>
-
-	<interface name="analysis.stddll" extends="analysis.dll">
-		<param name='OPEN_ENVIRONMENT' default='1'/>
-		<param name='UID2' default="20004c45"/>
-	</interface>
-
-	<interface name="analysis.stdexe" extends="analysis.exe">
-		<param name='OPEN_ENVIRONMENT' default='1'/>
-		<param name='UID2' default="20004c45"/>
-	</interface>
-
-	<interface name="analysis.stdlib" extends="analysis.lib">
-		<param name='OPEN_ENVIRONMENT' default='1'/>
-	</interface>
-
-	<interface name="analysis.textnotifier2" extends="analysis.dll">
-		<param name='UID2' default="101fe38b"/>
-	</interface>
-
-	<interface name="analysis.var" extends="analysis.dll">
-		<param name='TARGET_DEFS' default='$(KERNEL_MODE_DEF)'/>
-		<param name='TARGET_INCLUDES' default='$(KERNEL_MODE_INCLUDES)'/>	
-		<param name='FIRSTLIB' default="evar.lib"/>
-	</interface>
-	
-	<interface name="analysis.var2" extends="analysis.dll">
-		<param name='TARGET_DEFS' default='$(KERNEL_MODE_DEF)'/>
-		<param name='TARGET_INCLUDES' default='$(KERNEL_MODE_INCLUDES)'/>	
-		<param name='FIRSTLIB' default="evar.lib"/>
-	</interface>
-
-	<interface name="analysis.none" extends="analysis.mmp" flm="none.flm">
-	</interface>
-
-	<!-- TEMs are processed as if in an RVCT build -->
-
-	<interface name="analysis.extension" extends="base.extension" flm="template_ext.flm">
-		<param name='RVCTBIN'/>
-		<param name='RVCTLIB'/>
-		<param name='RVCTINC'/>
-	</interface>
-
-	<!-- types we don't much care about, but don't want any standard processing for -->
-
-	<interface name="analysis.implib" flm="null.flm">
-	</interface>
-
-</build>
-
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- analysis interfaces -->
+
+	<interface name="analysis.flm" extends="base.flm" abstract="true">
+
+		<!-- analysis specific -->
+
+		<param name='EXPORTHEADERS' default=''/>
+		<param name='RESOURCEFILES' default=''/>
+
+		<!-- generic -->
+
+		<param name='NMAKE'/>
+		<param name='NMAKEFLAGS'/>
+		<param name='OUTPUTPATH'/>
+		<param name='PRODUCT_INCLUDE'/>
+		<param name='RELEASEPATH'/>
+		<param name='REQUESTEDTARGETEXT' default=''/>
+		<param name='SBSV1MAKE'/>
+		<param name='VARIANTTYPE'/>
+		<param name='FULLVARIANTPATH'/>
+		<param name='SUPPORTS_STDCPP_NEWLIB' default='1'/>
+	</interface>
+
+	<interface name="analysis.mmp" extends="analysis.flm" abstract="true">
+		<param name='CAPABILITY' default='none'/>
+		<param name='DEFFILE' default=''/>
+		<param name='FIRSTLIB' default=''/>
+		<param name='KERNEL_MODE_DEF'/>
+		<param name='KERNEL_MODE_INCLUDES'/>			
+		<param name='LIBRARY' default=''/>
+		<param name='LINKAS' default=''/>
+		<param name='MMPDEFS' default=''/>
+		<param name='NOSTDCPP' default=''/>
+		<param name='OPEN_ENVIRONMENT' default=''/>
+		<param name='SOURCE' default=''/>
+		<param name='STATICLIBRARY' default=''/>
+		<param name='STDCPP' default=''/>
+		<param name='STDCPP_DEF'/>
+		<param name='STDCPP_INCLUDE'/>
+		<param name='SYSTEMINCLUDE' default=''/>
+		<param name='TARGET'/>
+		<param name='TARGETPATH' default=''/>
+		<param name='TARGETTYPE'/>
+		<param name='TARGET_DEFS' default=''/>
+		<param name='TARGET_INCLUDES' default=''/>
+		<param name='UID2' default='00000000'/>
+		<param name='UID2_ZERO_OVERRIDE' default=''/>
+		<param name='UID3' default='00000000'/>
+		<param name='USERINCLUDE' default=''/>
+		<param name='VERSION' default='1.0'/>
+		<param name='OPTION_GCCXML' default=''/>
+		<param name='VERSIONHEX' default='00010000'/>
+	</interface>
+
+	<interface name="analysis.all" extends="analysis.mmp" abstract="true" flm="gccxml.flm">
+		<param name='CC'/>
+		<param name='CDEFS'/>
+		<param name='CFLAGS'/>
+		<param name='CPPFLAGS'/>
+		<param name='CREATERFIFILE'/>
+		<param name='GNUCPP'/>
+		<param name='GNUSED'/>
+		<param name='GNUAWK'/>
+		<param name='OPT.DEFINE'/>
+		<param name='OPT.OUT'/>
+		<param name='OPT.PREINCLUDE'/>
+		<param name='OPT.SPLITINCLUDE'/>
+		<param name='OPT.SYSINCLUDE'/>
+		<param name='OPT.USERINCLUDE'/>
+		<param name='ZIP'/>
+	</interface>
+
+	<!-- basic types -->
+
+	<interface name="analysis.exe" extends="analysis.all">
+		<param name='FIRSTLIB' default="eexe.lib"/>
+		<param name='UID1' default="1000007a"/>
+	</interface>
+
+	<interface name="analysis.dll" extends="analysis.all">
+		<param name='FIRSTLIB' default="edll.lib"/>
+		<param name='UID1' default="10000079"/>
+	</interface>
+
+	<interface name="analysis.lib" extends="analysis.all">
+		<param name='FIRSTLIB' default="elib.lib"/>
+		<param name='UID1' default="00000000"/>
+	</interface>
+
+	<!-- variations on the basic types -->
+
+	<interface name="analysis.ani" extends="analysis.dll">
+		<param name='UID2' default="10003b22"/>
+	</interface>
+
+	<interface name="analysis.exexp" extends="analysis.exe">
+	</interface>
+
+	<interface name="analysis.fsy" extends="analysis.dll">
+		<param name='UID2_ZERO_OVERRIDE' default="100039df"/>
+	</interface>
+
+	<interface name="analysis.kdll" extends="analysis.dll">
+		<param name='TARGET_DEFS' default='$(KERNEL_MODE_DEF)'/>
+		<param name='TARGET_INCLUDES' default='$(KERNEL_MODE_INCLUDES)'/>		
+		<param name='FIRSTLIB' default="ekll.lib"/>
+	</interface>
+
+	<interface name="analysis.kext" extends="analysis.dll">
+		<param name='TARGET_DEFS' default='$(KERNEL_MODE_DEF)'/>
+		<param name='TARGET_INCLUDES' default='$(KERNEL_MODE_INCLUDES)'/>	
+		<param name='FIRSTLIB' default="eext.lib"/>
+	</interface>
+
+	<interface name="analysis.klib" extends="analysis.lib">
+		<param name='TARGET_DEFS' default='$(KERNEL_MODE_DEF)'/>
+	</interface>
+
+	<interface name="analysis.ldd" extends="analysis.dll">
+		<param name='TARGET_DEFS' default='$(KERNEL_MODE_DEF)'/>
+		<param name='TARGET_INCLUDES' default='$(KERNEL_MODE_INCLUDES)'/>	
+		<param name='FIRSTLIB' default="edev.lib"/>
+		<param name='UID2_ZERO_OVERRIDE' default="100000af"/>
+	</interface>
+
+	<interface name="analysis.pdd" extends="analysis.dll">
+		<param name='TARGET_DEFS' default='$(KERNEL_MODE_DEF)'/>
+		<param name='TARGET_INCLUDES' default='$(KERNEL_MODE_INCLUDES)'/>	
+		<param name='FIRSTLIB' default="edev.lib"/>
+		<param name='UID2_ZERO_OVERRIDE' default="100039d0"/>
+	</interface>
+
+	<interface name="analysis.pdl" extends="analysis.dll">
+		<param name='UID2' default="10003b1c"/>
+	</interface>
+
+	<interface name="analysis.plugin" extends="analysis.dll">
+		<param name='UID2' default="10009D8D"/>
+	</interface>
+
+	<interface name="analysis.resource" extends="base.resource" flm="gccxmlresource.flm">
+		<param name='CREATERFIFILE'/>
+		<param name='OUTPUTPATHOFFSET' default=''/>
+		<param name='MAIN_OUTPUTPATH' default=''/>
+		<param name='MAIN_TARGET_lower' default=''/>
+		<param name='MAIN_REQUESTEDTARGETEXT' default=''/>
+		<param name='RFIFILE' default=''/>
+	</interface>
+
+	<interface name="analysis.stddll" extends="analysis.dll">
+		<param name='OPEN_ENVIRONMENT' default='1'/>
+		<param name='UID2' default="20004c45"/>
+	</interface>
+
+	<interface name="analysis.stdexe" extends="analysis.exe">
+		<param name='OPEN_ENVIRONMENT' default='1'/>
+		<param name='UID2' default="20004c45"/>
+	</interface>
+
+	<interface name="analysis.stdlib" extends="analysis.lib">
+		<param name='OPEN_ENVIRONMENT' default='1'/>
+	</interface>
+
+	<interface name="analysis.textnotifier2" extends="analysis.dll">
+		<param name='UID2' default="101fe38b"/>
+	</interface>
+
+	<interface name="analysis.var" extends="analysis.dll">
+		<param name='TARGET_DEFS' default='$(KERNEL_MODE_DEF)'/>
+		<param name='TARGET_INCLUDES' default='$(KERNEL_MODE_INCLUDES)'/>	
+		<param name='FIRSTLIB' default="evar.lib"/>
+	</interface>
+	
+	<interface name="analysis.var2" extends="analysis.dll">
+		<param name='TARGET_DEFS' default='$(KERNEL_MODE_DEF)'/>
+		<param name='TARGET_INCLUDES' default='$(KERNEL_MODE_INCLUDES)'/>	
+		<param name='FIRSTLIB' default="evar.lib"/>
+	</interface>
+
+	<interface name="analysis.none" extends="analysis.mmp" flm="none.flm">
+	</interface>
+
+	<!-- TEMs are processed as if in an RVCT build -->
+
+	<interface name="analysis.extension" extends="base.extension" flm="template_ext.flm">
+		<param name='RVCTBIN'/>
+		<param name='RVCTLIB'/>
+		<param name='RVCTINC'/>
+	</interface>
+
+	<!-- types we don't much care about, but don't want any standard processing for -->
+
+	<interface name="analysis.implib" flm="null.flm">
+	</interface>
+
+</build>
+
--- a/sbsv2/raptor/lib/flm/base.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/base.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,127 +1,130 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- 
-	Fundamental interfaces from which others (platform or nonplatform specific) 
-	may be derived 
-     -->
-
-	<interface name="base.null" flm="null.flm">
-		<!-- use this for "targets" which should be no-op -->
-	</interface>
-	
-	<interface name="base.flm" abstract="true">
-		<param name='COMPONENT_META' default=''/>  <!-- bld.inf -->
-		<param name='COMPONENT_NAME' default=''/>  <!-- MP4 Player -->
-		<param name='COMPONENT_LAYER' default=''/> <!-- Multimedia -->
-		<param name='PROJECT_META' default=''/>     <!-- my.mmp  -->
-		<param name='DATE' default=''/>
-		<param name='DUMPBCINFO' default=''/>
-		<param name='PLATFORM' default=''/>
-		<param name='GNUMAKE38'/>
-		<param name='GNUCP'/>
-		<param name='GNUCAT'/>
-		<param name='GNUMKDIR'/>
-		<param name='GNUMV'/>
-		<param name='GNURM'/>
-		<param name='GNULN'/>
-		<param name='GNURMDIR'/>
-		<param name='GNUCHMOD'/>
-		<param name='GNUTOUCH'/>
-		<param name='GNUFIND'/>
-		<param name='GNUGREP'/>
-		<param name='GNUSED'/>
-		<param name='GNUSORT'/>
-		<param name='SBS_JAVATC' default=''/>
-		<param name='ZIP'/>
-		<param name='UNZIP'/>
-		<param name='GNUMD5SUM'/>
-		<param name='SAVESPACE' default=''/> <!-- remove intermediate files ASAP -->
-		<param name='WHATLOG' default=''/>   <!-- emit formatted releasable info into the logs during the build -->
-		<param name='USE_PROFILER_FEEDBACK' default=''/> <!-- use the profiler feedback file for the builds -->
-		<param name='ARM_PROFILER_FILE' default=''/>
-	</interface>
-	<interface name="base.extension" extends="base.flm" flm="template_ext.flm">
-		<param name='TEMCOUNT'/>
-		<param name='TEMMAKE' default='$(GNUMAKE38)'/>
-		<param name='EPOCROOT'/>
-		<param name='TEMPLATE_EXTENSION_MAKEFILE'/>
-		<param name='PRODUCT_INCLUDE'/>
-		<param name='EPOCBLD'/>
-		<param name='TO_BLDINF'/>
-		<param name='TO_ROOT'/>
-		<param name='EXTENSION_ROOT'/>
-		<param name='O._MEMBERS' default=""/>
-		<param name='VARIANTPLATFORM'/>
-		<param name='VARIANTTYPE'/>
-		<param name='PLATFORM' default='$(VARIANTPLATFORM)'/>
-		<param name='PLATFORM_PATH' default='$(VARIANTPLATFORM)'/>
-		<param name='CFG' default='$(VARIANTTYPE)'/>
-		<param name='CFG_PATH' default='$(VARIANTTYPE)'/>
-		<param name='NMAKE' default=''/>
-		<param name='NMAKEFLAGS' default=''/>
-		<param name='SBSV1MAKE' default=''/>
-		<paramgroup pattern='^O\.[^ \t]+$' default=""/>
-	</interface>
-	<interface name="base.stringtable" extends="base.flm" flm="stringtable.flm">
-		<param name='EPOCROOT'/>
-		<param name='SOURCE'/>
-		<param name='EXPORTPATH'/>
-		<param name='HEADERONLY' default=''/>
-		<param name='OUTPUTPATH'/>
-		<param name='STRINGTABLE'/>
-		<param name='TARGET'/>
-	</interface>
-	<interface name="base.bitmap" extends="base.flm" flm="bitmap.flm">
-		<param name='BINCOPYDIRS' default=''/>
-		<param name='BMCONV'/>
-		<param name='EPOCROOT'/>
-		<param name='HEADER' default=''/>
-		<param name='OUTPUTPATH'/>
-		<param name='SOURCE'/>
-		<param name='BMTARGET'/>
-		<param name='TARGETPATH' default=''/>
-	</interface>
-	<interface name="base.resource" extends="base.flm" flm="resource.flm">
-		<param name='BINCOPYDIRS' default=''/>
-		<param name='MMPDEFS' default=''/>
-		<param name='GNUCPP'/>
-		<param name='GNUSED'/>
-		<param name='EPOCROOT'/>
-		<param name='HEADER' default=''/>
-		<param name='HEADERONLY' default=''/>
-		<param name='LANGUAGES' default='sc'/>
-		<param name='PRODUCT_INCLUDE'/>
-		<param name='RCOMP'/>
-		<param name='OUTPUTPATH'/>
-		<param name='RSGDEPENDS' default=''/>
-		<param name='SOURCE'/>
-		<param name='SYSTEMINCLUDE'/>
-		<param name='USERINCLUDE'/>
-		<param name='TARGET'/>
-		<param name='TARGET_lower'/>
-		<param name='TARGETPATH' default=''/>
-		<param name='UID1' default="1000007a"/>
-		<param name='UID2' default='00000000'/>
-		<param name='UID3' default='00000000'/>
-	</interface>
-	<interface name="base.export" extends="base.null">
-		<!-- exports are done in Python -->
-	</interface>
-	<interface name="base.ext_makefile" extends="base.flm" flm="gnumakefile.flm">
-		<param name='CFG' default='$(VARIANTTYPE)'/>
-		<param name='EPOCROOT'/>
-		<param name='EXTENSION_ROOT'/>
-		<param name='DIRECTORY'/>
-		<param name='EXTMAKEFILENAME'/>
-		<param name='EPOCBLD'/>
-		<param name='VARIANTPLATFORM'/>
-		<param name='PLATFORM' default='$(VARIANTPLATFORM)'/>
-		<param name='TO_ROOT'/>
-		<param name='TO_BLDINF'/>
-		<param name='USENMAKE' default=''/>
-		<param name='NMAKE' default=''/>
-		<param name='NMAKEFLAGS' default=''/>
-		<param name='SBSV1MAKE' default=''/>
-	</interface>
-
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- 
+	Fundamental interfaces from which others (platform or nonplatform specific) 
+	may be derived 
+     -->
+
+	<interface name="base.null" flm="null.flm">
+		<!-- use this for "targets" which should be no-op -->
+	</interface>
+	
+	<interface name="base.flm" abstract="true">
+		<param name='COMPONENT_META' default=''/>  <!-- bld.inf -->
+		<param name='COMPONENT_NAME' default=''/>  <!-- MP4 Player -->
+		<param name='COMPONENT_LAYER' default=''/> <!-- Multimedia -->
+		<param name='PROJECT_META' default=''/>     <!-- my.mmp  -->
+		<param name='DATE' default=''/>
+		<param name='DUMPBCINFO' default=''/>
+		<param name='FLMDEBUG'  default=''/>
+		<param name='PLATFORM' default=''/>
+		<param name='PYTHON' default=''/> <!-- allow python scripts to be used in general flms -->
+		<param name='GNUMAKE38'/>
+		<param name='GNUCP'/>
+		<param name='GNUCAT'/>
+		<param name='GNUMKDIR'/>
+		<param name='GNUMV'/>
+		<param name='GNURM'/>
+		<param name='GNULN'/>
+		<param name='GNURMDIR'/>
+		<param name='GNUCHMOD'/>
+		<param name='GNUTOUCH'/>
+		<param name='GNUFIND'/>
+		<param name='GNUGREP'/>
+		<param name='GNUSED'/>
+		<param name='GNUSORT'/>
+		<param name='SBS_JAVATC' default=''/>
+		<param name='ZIP'/>
+		<param name='UNZIP'/>
+		<param name='GNUMD5SUM'/>
+		<param name='SAVESPACE' default=''/> <!-- remove intermediate files ASAP -->
+		<param name='WHATLOG' default=''/>   <!-- emit formatted releasable info into the logs during the build -->
+		<param name='USE_PROFILER_FEEDBACK' default=''/> <!-- use the profiler feedback file for the builds -->
+		<param name='ARM_PROFILER_FILE' default=''/>
+	</interface>
+	<interface name="base.extension" extends="base.flm" flm="template_ext.flm">
+		<param name='TEMCOUNT'/>
+		<param name='TEMMAKE' default='$(GNUMAKE38)'/>
+		<param name='EPOCROOT'/>
+		<param name='TEMPLATE_EXTENSION_MAKEFILE'/>
+		<param name='PRODUCT_INCLUDE'/>
+		<param name='EPOCBLD'/>
+		<param name='TO_BLDINF'/>
+		<param name='TO_ROOT'/>
+		<param name='EXTENSION_ROOT'/>
+		<param name='O._MEMBERS' default=""/>
+		<param name='VARIANTPLATFORM'/>
+		<param name='VARIANTTYPE'/>
+		<param name='PLATFORM' default='$(VARIANTPLATFORM)'/>
+		<param name='PLATFORM_PATH' default='$(VARIANTPLATFORM)'/>
+		<param name='CFG' default='$(VARIANTTYPE)'/>
+		<param name='CFG_PATH' default='$(VARIANTTYPE)'/>
+		<param name='NMAKE' default=''/>
+		<param name='NMAKEFLAGS' default=''/>
+		<param name='SBSV1MAKE' default=''/>
+		<paramgroup pattern='^O\.[^ \t]+$' default=""/>
+	</interface>
+	<interface name="base.stringtable" extends="base.flm" flm="stringtable.flm">
+		<param name='EPOCROOT'/>
+		<param name='SOURCE'/>
+		<param name='EXPORTPATH'/>
+		<param name='HEADERONLY' default=''/>
+		<param name='OUTPUTPATH'/>
+		<param name='STRINGTABLE'/>
+		<param name='TARGET'/>
+	</interface>
+	<interface name="base.bitmap" extends="base.flm" flm="bitmap.flm">
+		<param name='BINCOPYDIRS' default=''/>
+		<param name='BMCONV'/>
+		<param name='EPOCROOT'/>
+		<param name='HEADER' default=''/>
+		<param name='OUTPUTPATH'/>
+		<param name='SOURCE'/>
+		<param name='BMTARGET'/>
+		<param name='TARGETPATH' default=''/>
+	</interface>
+	<interface name="base.resource" extends="base.flm" flm="resource.flm">
+		<param name='BINCOPYDIRS' default=''/>
+		<param name='DEPCRUNCH'/>
+		<param name='MMPDEFS' default=''/>
+		<param name='GNUCPP'/>
+		<param name='GNUSED'/>
+		<param name='EPOCROOT'/>
+		<param name='HEADER' default=''/>
+		<param name='HEADERONLY' default=''/>
+		<param name='LANGUAGES' default='sc'/>
+		<param name='PRODUCT_INCLUDE'/>
+		<param name='RCOMP'/>
+		<param name='OUTPUTPATH'/>
+		<param name='RSGDEPENDS' default=''/>
+		<param name='SOURCE'/>
+		<param name='SYSTEMINCLUDE'/>
+		<param name='USERINCLUDE'/>
+		<param name='TARGET'/>
+		<param name='TARGET_lower'/>
+		<param name='TARGETPATH' default=''/>
+		<param name='UID1' default="1000007a"/>
+		<param name='UID2' default='00000000'/>
+		<param name='UID3' default='00000000'/>
+	</interface>
+	<interface name="base.export" extends="base.null">
+		<!-- exports are done in Python -->
+	</interface>
+	<interface name="base.ext_makefile" extends="base.flm" flm="gnumakefile.flm">
+		<param name='CFG' default='$(VARIANTTYPE)'/>
+		<param name='EPOCROOT'/>
+		<param name='EXTENSION_ROOT'/>
+		<param name='DIRECTORY'/>
+		<param name='EXTMAKEFILENAME'/>
+		<param name='EPOCBLD'/>
+		<param name='VARIANTPLATFORM'/>
+		<param name='PLATFORM' default='$(VARIANTPLATFORM)'/>
+		<param name='TO_ROOT'/>
+		<param name='TO_BLDINF'/>
+		<param name='USENMAKE' default=''/>
+		<param name='NMAKE' default=''/>
+		<param name='NMAKEFLAGS' default=''/>
+		<param name='SBSV1MAKE' default=''/>
+	</interface>
+
+</build>
--- a/sbsv2/raptor/lib/flm/bitmap.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/bitmap.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,182 +1,130 @@
-# 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:
-# Header file exporting Function Like Makefile (FLM)
-# The file destinations  relative to EPOCROOT
-# 
-#
-
-## Parameters that are expected:
-# BMCONV
-# EPOCROOT
-# HEADER
-# OUTPUTPATH
-# SOURCE
-# BMTARGET
-# TARGETPATH
-# BINCOPYDIRS
-
-ifneq ($(TARGETPATH),)
-DATAPATH:=$(subst //,/,$(EPOCROOT)/epoc32/data/z/$(TARGETPATH))
-else
-DATAPATH:=$(subst //,/,$(EPOCROOT)/epoc32/data)
-endif
-CREATABLEPATHS:=$(DATAPATH) $(OUTPUTPATH)
-
-BITMAPFILE:=$(subst //,/,$(DATAPATH)/$(BMTARGET))
-
-# additional binary resource copies performed based on BINCOPYDIRS
-MBMCOPYDIRS:=
-MBMCOPYFILES:=
-ifneq ($(BINCOPYDIRS),)
-  MBMCOPYDIRS:=$(subst //,/,$(patsubst %,%/$(if $(TARGETPATH),/z/$(TARGETPATH),),$(BINCOPYDIRS)))
-  CREATABLEPATHS:=$(CREATABLEPATHS) $(MBMCOPYDIRS)
-  MBMCOPYFILES:=$(subst //,/,$(patsubst %, %/$(notdir $(BITMAPFILE)),$(MBMCOPYDIRS)))
-endif
-
-
-ifneq ($(HEADER),)
-BITMAPHEADER:=$(subst //,/,$(EPOCROOT)/epoc32/include/$(basename $(BMTARGET)).mbg)
-else
-BITMAPHEADER:=
-endif
-
-
-# SOURCE is something like "DEPTH=2 FILE=/var/local/fred.bmp"
-# Extract the file parts for the dependencies.
-# Generate -2/var/local/fred.bmp for the command-line argument.
-SOURCEDEPS:=$(subst //,/,$(subst FILE=,,$(filter FILE=%,$(SOURCE))))
-SOURCEARGS:=$(subst //,/,$(subst DEPTH=,-,$(subst $(CHAR_SPACE)FILE=,,$(SOURCE))))
-
-BMCONVCMDFILE:=$(OUTPUTPATH)/$(BMTARGET)_bmconvcommands
-RELEASEABLES:=$(BITMAPHEADER) $(BITMAPFILE)
-CLEANTARGETS:=$(BITMAPHEADER) $(BITMAPFILE) $(BMCONVCMDFILE)
-
-# The groupbmpin10 macro allows us to construct a command file, 10 
-# bitmap objects at a time to avoid limits on argument lengths and 
-# sizes on Windows.
-define groupbmpin10
-	$(if $1,$(shell echo -e $(foreach L,$(wordlist 1,10,$1),"$(L)\\n") >>$(BMCONVCMDFILE)),)
-	$(if $1,$(call groupbmpin10,$(wordlist 11,$(words $1),$1)))
-endef
-
-GUARD:=$(call sanitise,TARGET_$(BITMAPFILE))
-define generatebitmap
-$(GUARD):=1
-
-BITMAP:: $(RELEASEABLES)
-
-ifneq ($(BITMAPHEADER),)
-$(BITMAPHEADER): $(BITMAPFILE)
-endif
-
-# Create commandfile during parse so that the log is not littered with 
-# these commands in parallel builds.
-$(info <bmconvcmdfile>)
-$(info $(BMCONVCMDFILE))
-$(shell $(GNUMKDIR) -p "$(dir $(BMCONVCMDFILE))")
-$(if $(BITMAPHEADER),$(shell echo -e "-h$(BITMAPHEADER)\n$(BITMAPFILE)" >$(BMCONVCMDFILE)),$(shell echo "$(BITMAPFILE)" >$(BMCONVCMDFILE)) )
-$(call groupbmpin10, $(SOURCEARGS))
-$(info </bmconvcmdfile>)
-
-$(BITMAPFILE): $(SOURCEDEPS) $(BMCONV) 
-	$(call startrule,bitmapcompile,FORCESUCCESS) \
-	$(BMCONV) $(BMCONVCMDFILE) \
-	$(call endrule,bitmapcompile)
-
-endef
-
-
-# Some builds require further copies of the generated mbm binaries
-define copybitmap
-
-BITMAP:: $(MBMCOPYFILES)
-
-$(MBMCOPYFILES): $(BITMAPFILE) 
-	$(call startrule,bitmapcopy,FORCESUCCESS) \
-	$(GNUCP) $$< $$@ \
-	$(call endrule,bitmapcopy)
-
-CLEANTARGETS:=$(CLEANTARGETS) $(MBMCOPYFILES)
-endef
-
-
-ifeq ($($(GUARD)),)
-$(eval $(call generatebitmap))
-endif
-
-ifneq ($(MBMCOPYFILES),)
-$(eval $(call copybitmap))
-endif
-
-################################### localisation #########################################
-## copy .bmp files to localisation
-
-# $(BMPFILES) is a list of bmp files in src
-BMPFILES:=$(subst FILE=,,$(filter FILE=%,$(SOURCE)))
-BMBASENAME:=$(call lowercase,$(basename $(BMTARGET)))
-BMPCOPYFILES:=
-BMPCOPYDIR:=$(EPOCROOT)/epoc32/localisation/$(BMBASENAME)/mbm
-$(call makepath,$(BMPCOPYDIR))
-
-define copyBMP
-# $(1) is the source .bmp file
-# $(2) is the (lower cased) copy in localisation 
-
-ifneq ($(BINCOPYDIRS),)
-BITMAP:: $(2)
-
-$(2): $(1)
-	$(call startrule,bmpfilecopy,FORCESUCCESS) \
-	$(GNUCP) $(1) $(2) && $(GNUCHMOD) +rw $(2) \
-	$(call endrule,bmpfilecopy)
-
-CLEANTARGETS:=$$(CLEANTARGETS) $(2)
-endif
-
-BMPCOPYFILES:=$$(BMPCOPYFILES) $(2)
-endef
-
-$(foreach BMP,$(BMPFILES),$(eval $(call copyBMP,$(BMP),$(BMPCOPYDIR)/$(call lowercase,$(notdir $(BMP))))))
-
-## create and edit info files for bitmap files in localisation/group
-INFOFILE:=$(EPOCROOT)/epoc32/localisation/group/$(BMBASENAME).info
-DEPTH:=$(subst DEPTH=,,$(filter DEPTH=%,$(SOURCE)))
-BMP:=$(notdir $(BMPFILES))
-DEPTHBMP:=$(subst _,\,$(join $(patsubst %,/%,$(DEPTH)),$(patsubst %,_%,$(BMP))))
-
-define bmpInfo
-
-BITMAP::$(INFOFILE)
-
-$(INFOFILE)::
-	@if [ ! -d $(EPOCROOT)/epoc32/localisation/group ]; then $(GNUMKDIR) -p $(EPOCROOT)/epoc32/localisation/group; fi
-	@if [ ! -f $$@ ]; then echo "DATADIR: /$(BMBASENAME)" > $$@ ; fi
-	@echo -e "\n/z$(TARGETPATH)/$(BMTARGET) : $(DEPTHBMP)" >> $$@
-
-CLEANTARGETS:=$$(CLEANTARGETS) $(INFOFILE)
-endef
-
-$(eval $(call bmpInfo))
-
-# end of localisation #########################################################
-
-## Clean up
-$(eval $(call GenerateStandardCleanTarget,$(CLEANTARGETS) ,$(CREATABLEPATHS)))
-$(call makepath,$(CREATABLEPATHS))
-$(call makepathfor,$(BITMAPHEADER))
-
-# for the abld -what target
-BMPRELEASEABLES:=$(RELEASEABLES) $(MBMCOPYFILES) $(BMPCOPYFILES) $(INFOFILE)
-$(eval $(call whatmacro,$(BMPRELEASEABLES),WHATBITMAP))
-
+# 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:
+# Header file exporting Function Like Makefile (FLM)
+# The file destinations  relative to EPOCROOT
+# 
+#
+
+## Parameters that are expected:
+# BMCONV
+# EPOCROOT
+# HEADER
+# OUTPUTPATH
+# SOURCE
+# BMTARGET
+# TARGETPATH
+# BINCOPYDIRS
+
+ifneq ($(TARGETPATH),)
+DATAPATH:=$(subst //,/,$(EPOCROOT)/epoc32/data/z/$(TARGETPATH))
+else
+DATAPATH:=$(subst //,/,$(EPOCROOT)/epoc32/data)
+endif
+CREATABLEPATHS:=$(DATAPATH) $(OUTPUTPATH)
+
+BITMAPFILE:=$(subst //,/,$(DATAPATH)/$(BMTARGET))
+
+# additional binary resource copies performed based on BINCOPYDIRS
+MBMCOPYDIRS:=
+MBMCOPYFILES:=
+ifneq ($(BINCOPYDIRS),)
+  MBMCOPYDIRS:=$(subst //,/,$(patsubst %,%/$(if $(TARGETPATH),/z/$(TARGETPATH),),$(BINCOPYDIRS)))
+  CREATABLEPATHS:=$(CREATABLEPATHS) $(MBMCOPYDIRS)
+  MBMCOPYFILES:=$(subst //,/,$(patsubst %, %/$(notdir $(BITMAPFILE)),$(MBMCOPYDIRS)))
+endif
+
+
+ifneq ($(HEADER),)
+BITMAPHEADER:=$(subst //,/,$(EPOCROOT)/epoc32/include/$(basename $(BMTARGET)).mbg)
+else
+BITMAPHEADER:=
+endif
+
+
+# SOURCE is something like "DEPTH=2 FILE=/var/local/fred.bmp"
+# Extract the file parts for the dependencies.
+# Generate -2/var/local/fred.bmp for the command-line argument.
+SOURCEDEPS:=$(subst //,/,$(subst FILE=,,$(filter FILE=%,$(SOURCE))))
+SOURCEARGS:=$(subst //,/,$(subst DEPTH=,-,$(subst $(CHAR_SPACE)FILE=,,$(SOURCE))))
+
+BMCONVCMDFILE:=$(OUTPUTPATH)/$(BMTARGET)_bmconvcommands
+RELEASEABLES:=$(BITMAPHEADER) $(BITMAPFILE)
+CLEANTARGETS:=$(BMCONVCMDFILE)
+
+# The groupbmpin10 macro allows us to construct a command file, 10 
+# bitmap objects at a time to avoid limits on argument lengths and 
+# sizes on Windows.
+define groupbmpin10
+	$(if $1,$(shell echo -e $(foreach L,$(wordlist 1,10,$1),"$(L)\\n") >>$(BMCONVCMDFILE)),)
+	$(if $1,$(call groupbmpin10,$(wordlist 11,$(words $1),$1)))
+endef
+
+GUARD:=$(call sanitise,TARGET_$(BITMAPFILE))
+define generatebitmap
+$(GUARD):=1
+
+BITMAP:: $(RELEASEABLES)
+
+ifneq ($(BITMAPHEADER),)
+$(BITMAPHEADER): $(BITMAPFILE)
+endif
+
+# Create commandfile during parse so that the log is not littered with 
+# these commands in parallel builds.
+$(info <bmconvcmdfile>)
+$(info $(BMCONVCMDFILE))
+$(shell $(GNUMKDIR) -p "$(dir $(BMCONVCMDFILE))")
+$(if $(BITMAPHEADER),$(shell echo -e "-h$(BITMAPHEADER)\n$(BITMAPFILE)" >$(BMCONVCMDFILE)),$(shell echo "$(BITMAPFILE)" >$(BMCONVCMDFILE)) )
+$(call groupbmpin10, $(SOURCEARGS))
+$(info </bmconvcmdfile>)
+
+$(BITMAPFILE): $(SOURCEDEPS) $(BMCONV) 
+	$(call startrule,bitmapcompile,FORCESUCCESS) \
+	$(BMCONV) $(BMCONVCMDFILE) \
+	$(call endrule,bitmapcompile)
+
+endef
+
+
+# Some builds require further copies of the generated mbm binaries
+define copybitmap
+
+BITMAP:: $(MBMCOPYFILES)
+
+$(MBMCOPYFILES): $(BITMAPFILE) 
+	$(call startrule,bitmapcopy,FORCESUCCESS) \
+	$(GNUCP) $$< $$@ \
+	$(call endrule,bitmapcopy)
+
+endef
+
+
+ifeq ($($(GUARD)),)
+$(eval $(call generatebitmap))
+endif
+
+ifneq ($(MBMCOPYFILES),)
+$(eval $(call copybitmap))
+endif
+
+
+## Clean up
+$(call raptor_clean,$(CLEANTARGETS))
+$(call makepath,$(CREATABLEPATHS))
+$(call makepathfor,$(BITMAPHEADER))
+
+# for the abld -what target
+BMPRELEASEABLES:=$(RELEASEABLES) $(MBMCOPYFILES)
+$(call raptor_release,$(BMPRELEASEABLES),BITMAP)
+
--- a/sbsv2/raptor/lib/flm/booleanlogic.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/booleanlogic.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,61 +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: 
-# operators for boolean logic, including a case 
-# sensitive equality operator
-#
-
-
-define not
-$(if $1,,1)
-endef
-
-define xor
-$(and $(or $1,$2),$(call not,$1,$2))
-endef
-
-define equal
-$(if $(1:$(2)=),,$(if $(2:$(1)=),,1))
-endef
-
-define equal_debug
-$(info equal $1 $2 )$(if $(1:$(2)=),,$(if $(2:$(1)=),,1))
-endef
-
-# $(call isoneof,fred, alice bob james fred joe)  # returns 1
-define isoneof
-$(if $2,$(or $(call equal,$1,$(word 1,$2)),$(call isoneof,$(1),$(wordlist 2,$(words $(2)),$(2)))),)
-endef
-
-define isoneof_debug
-$(info one:$1 LIST: $2 nextCAR: $(word 1,$2) nextCDR: $(wordlist 2,$(words $2),$2))$(if $2,$(or $(call equal,$1,$(word 1,$2)),$(call isoneof,$(1),$(wordlist 2,$(words $(2)),$(2)))),)
-endef
-
-#testboolean::
-#	@echo -e "(call equal,dll,dll)            :  $(call equal,dll,dll)"
-#	@echo -e "(call equal,,dll)               :  $(call equal,,dll)"
-#	@echo -e "(call equal,thingdllthing,dll)  :  $(call equal,thingdllthing,dll)"
-#	@echo -e "(call equal,dll,thingdllthing)  :  $(call equal,dll,thingdllthing)"
-#	@echo -e "(call equal,dll,)               :  $(call equal,dll,)"
-#	@echo -e "(call equal,,)                  :  $(call equal,,)"
-#	@echo -e "(call equal,dlldlldll,dll)      :  $(call equal,dlldlldll,dll)"
-#	@echo -e "(call equal,dll,dlldlldll)      :  $(call equal,dll,dlldlldll)"
-#	@echo ""
-#	@echo -e '(call isoneof,fred, nobby cheery fred detritus ) :  $(call isoneof,fred, nobby cheery fred detritus) '
-#	@echo -e '(call isoneof,nobby, cheery fred carrot angiur)  :  $(call isoneof,nobby, cheery fred carrot angiur) '
-#	@echo -e '(call isoneof,vimes,vetinari) :  $(call isoneof,vimes,vetinari) '
-#	@echo -e '(call isoneof,vetinari,) :  $(call isoneof,vetinari,) '
-#	@echo -e '(call isoneof,vetinari,vetinari) :  $(call isoneof,vetinari,vetinari) '
-
-
+#
+# 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: 
+# operators for boolean logic, including a case 
+# sensitive equality operator
+#
+
+
+define not
+$(if $1,,1)
+endef
+
+define xor
+$(and $(or $1,$2),$(call not,$1,$2))
+endef
+
+define equal
+$(if $(1:$(2)=),,$(if $(2:$(1)=),,1))
+endef
+
+define equal_debug
+$(info equal $1 $2 )$(if $(1:$(2)=),,$(if $(2:$(1)=),,1))
+endef
+
+# $(call isoneof,fred, alice bob james fred joe)  # returns 1
+define isoneof
+$(if $2,$(or $(call equal,$1,$(word 1,$2)),$(call isoneof,$(1),$(wordlist 2,$(words $(2)),$(2)))),)
+endef
+
+define isoneof_debug
+$(info one:$1 LIST: $2 nextCAR: $(word 1,$2) nextCDR: $(wordlist 2,$(words $2),$2))$(if $2,$(or $(call equal,$1,$(word 1,$2)),$(call isoneof,$(1),$(wordlist 2,$(words $(2)),$(2)))),)
+endef
+
+#testboolean::
+#	@echo -e "(call equal,dll,dll)            :  $(call equal,dll,dll)"
+#	@echo -e "(call equal,,dll)               :  $(call equal,,dll)"
+#	@echo -e "(call equal,thingdllthing,dll)  :  $(call equal,thingdllthing,dll)"
+#	@echo -e "(call equal,dll,thingdllthing)  :  $(call equal,dll,thingdllthing)"
+#	@echo -e "(call equal,dll,)               :  $(call equal,dll,)"
+#	@echo -e "(call equal,,)                  :  $(call equal,,)"
+#	@echo -e "(call equal,dlldlldll,dll)      :  $(call equal,dlldlldll,dll)"
+#	@echo -e "(call equal,dll,dlldlldll)      :  $(call equal,dll,dlldlldll)"
+#	@echo ""
+#	@echo -e '(call isoneof,fred, nobby cheery fred detritus ) :  $(call isoneof,fred, nobby cheery fred detritus) '
+#	@echo -e '(call isoneof,nobby, cheery fred carrot angiur)  :  $(call isoneof,nobby, cheery fred carrot angiur) '
+#	@echo -e '(call isoneof,vimes,vetinari) :  $(call isoneof,vimes,vetinari) '
+#	@echo -e '(call isoneof,vetinari,) :  $(call isoneof,vetinari,) '
+#	@echo -e '(call isoneof,vetinari,vetinari) :  $(call isoneof,vetinari,vetinari) '
+
+
--- a/sbsv2/raptor/lib/flm/build.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/build.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,75 +1,76 @@
-# 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:
-#
-#
-
-# Parameters:
-# COMPONENT_PATHS
-# CONFIGS
-#
-
-CREATABLEPATHS:=
-CLEANTARGETS:=
-
-.PHONY:: PP_EXPORTS
-
-
-SBS := $(subst \,/,$(SBS_HOME)/bin/sbs)
-
-define doexports
-PP_EXPORTS::
-	$(call startrule,makefile_generation_exports) \
-	export TALON_DESCRAMBLE=0; \
-	$(SBS) --export-only $(component_list) $(config_list) -f- -m $(SBS_BUILD_DIR)/makefiles_export.mk $(cli_options)  --mo=DESCRAMBLE:=  --mo=TALON_DESCRAMBLE:=0 | $(GNUSED) 's#]I*]>#XXX#' \
-	$(call endrule,makefile_generation_exports)
-
-CLEANTARGETS:=$$(CLEANTARGETS) $(SBS_BUILD_DIR)/makefiles_export.mk
-endef
-
-# Generate makefiles for particular bldinf
-# $(1) = source target source target......
-define generate_makefiles
-
-$$(info XXX component_list=$(COMPONENT_PATHS) makefile=$(MAKEFILE_PATH))
-
-ifeq ($(NO_BUILD),1)
-ALL:: $(MAKEFILE_PATH)
-else
-include $(MAKEFILE_PATH)
-endif
-
-$(MAKEFILE_PATH): $(COMPONENT_PATHS) | PP_EXPORTS 
-	$(call startrule,makefile_generation) \
-	export TALON_DESCRAMBLE=0; \
-	$(SBS) --toolcheck=off -n $(CLI_OPTIONS) $(component_list) $(config_list) -m $$@ -f- --mo=DESCRAMBLE:= --mo=TALON_DESCRAMBLE:=0  | $(GNUSED) 's#\]\][>]#XXX#' && \
-	$(MAKE) -j 8 -f $$@.resource_deps \
-	$(call endrule,makefile_generation)
-
-CLEANTARGETS:=$$(CLEANTARGETS) $(MAKEFILE_PATH) 
-
-endef
-
-# Create config list for commands
-config_list:=$(addprefix -c ,$(CONFIGS))
-component_list:=$(addprefix -b ,$(COMPONENT_PATHS))
-$(info COMFIG_LIST: $(config_list))
-
-$(eval $(doexports))
-
-# Create the Makefiles
-$(eval $(call generate_makefiles))
-
-$(eval $(call GenerateStandardCleanTarget,$(CLEANTARGETS),$(CREATABLEPATHS),))
-$(call makepath,$(CREATABLEPATHS))
-
+# 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:
+#
+#
+
+# Parameters:
+# COMPONENT_PATHS
+# CONFIGS
+#
+
+CREATABLEPATHS:=
+CLEANTARGETS:=
+
+.PHONY:: PP_EXPORTS
+
+ifneq ($(filter win,$(HOSTPLATFORM)),)
+SBS:=$(subst \,/,$(SBS_HOME)/bin/sbs.bat)
+else
+SBS:=$(SBS_HOME)/bin/sbs
+endif
+
+
+define doexports
+PP_EXPORTS::
+	$(call startrule,makefile_generation_exports) \
+	$(SBS) --toolcheck=off --export-only $(component_list) $(config_list) -f- -m $(MAKEFILE_PATH).exports $(CLI_OPTIONS)  \
+	$(call endrule,makefile_generation_exports)
+
+CLEANTARGETS:=$$(CLEANTARGETS) $(MAKEFILE_PATH).exports 
+endef
+
+# Generate makefiles for particular bldinf
+# $(1) = source target source target......
+define generate_makefiles
+
+ALL:: $(MAKEFILE_PATH)
+
+$(MAKEFILE_PATH): $(COMPONENT_PATHS) $(if $(DOEXPORT),| PP_EXPORTS )
+	$(call startrule,makefile_generation) \
+	$(SBS) --noexport --toolcheck=off -n $(CLI_OPTIONS) $(component_list) $(config_list) -m $$@ -f- \
+	$(call endrule,makefile_generation)
+
+CLEANTARGETS:=$$(CLEANTARGETS) $(MAKEFILE_PATH) 
+
+endef
+
+# Create config list for commands
+config_list:=$(addprefix -c ,$(CONFIGS))
+component_list:=$(addprefix -b ,$(COMPONENT_PATHS))
+
+$(if $(FLMDEBUG),$(info <debug>build.flm: configlist: $(config_list)</debug>))
+
+# Do exports only if asked. This doesn't work brilliantly in emake
+# since exports are often duplicated in some components - leads to conflicts 
+# and rebuilds.  Better to export before trying to do parallel parsing at all.
+$(if $(DOEXPORT),$(eval $(doexports)),$(if $(FLMDEBUG),$(info <debug>build.flm: Exports off </debug>)))
+
+# Create the Makefiles
+$(eval $(call generate_makefiles))
+
+CREATABLEPATHS:=$(CREATABLEPATHS) $(dir $(MAKEFILE_PATH))
+
+$(eval $(call GenerateStandardCleanTarget,$(CLEANTARGETS),$(CREATABLEPATHS),))
+$(call makepath,$(CREATABLEPATHS))
+
--- a/sbsv2/raptor/lib/flm/build.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/build.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,14 +1,15 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-
-	<interface name="build.makefiles" extends="base.flm" flm='build.flm' >
-		<param name='SBS_BUILD_DIR' /> 
-		<param name='DATE' /> 
-		<param name='COMPONENT_PATHS' />
-		<param name='MAKEFILE_PATH' />
-		<param name='CONFIGS' default=''/>
-		<param name='CLI_OPTIONS' default=''/>
-		<param name='NO_BUILD' default='' />
-	</interface>
-
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+
+	<interface name="build.makefiles" extends="base.flm" flm='build.flm' >
+		<param name='SBS_BUILD_DIR' /> 
+		<param name='DATE' /> 
+		<param name='COMPONENT_PATHS' />
+		<param name='MAKEFILE_PATH' />
+		<param name='CONFIGS' default=''/>
+		<param name='CLI_OPTIONS' default=''/>
+		<param name='NO_BUILD' default='' />
+		<param name='DOEXPORT' default='1' />
+	</interface>
+
+</build>
--- a/sbsv2/raptor/lib/flm/config.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/config.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,13 +1,13 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- interfaces which do not correspond to target types:
-         they are added automatically to the build specification for a given
-         build configuration if listed in its INTERFACE.config variable -->
-
-	<interface name="Symbian.config.default" flm="config/default.flm">
-		<param name='EPOCROOT'/>
-		<param name='ELF2E32' default=''/>
-		<param name='WHATLOG' default=''/>
-	</interface>
-
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- interfaces which do not correspond to target types:
+         they are added automatically to the build specification for a given
+         build configuration if listed in its INTERFACE.config variable -->
+
+	<interface name="Symbian.config.default" flm="config/default.flm">
+		<param name='EPOCROOT'/>
+		<param name='ELF2E32' default=''/>
+		<param name='WHATLOG' default=''/>
+	</interface>
+
+</build>
--- a/sbsv2/raptor/lib/flm/config/default.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/config/default.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,61 +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:
-# config/default.flm
-# Default build-configuration-wide rules and dependencies.
-# 
-#
-
-# put things in here that depend on EPOCROOT and 
-# therefore cannot go in globals.mk
-
-# metaflm depends on variables set in the configuration
-include $(FLMHOME)/metaflm.mk
-
-# TEM dependencies
-EPOC32BUILD:=$(EPOCROOT)/epoc32/build
-
-.PHONY:: $(EPOC32BUILD)/TEM_MAKMAKE
-.PHONY:: $(EPOC32BUILD)/TEM_RESOURCE
-.PHONY:: $(EPOC32BUILD)/TEM_BLD
-.PHONY:: $(EPOC32BUILD)/TEM_FINAL
-
-$(EPOC32BUILD)/TEM_MAKMAKE:: EXPORT
-$(EPOC32BUILD)/TEM_RESOURCE:: $(EPOC32BUILD)/TEM_MAKMAKE
-$(EPOC32BUILD)/TEM_BLD:: $(EPOC32BUILD)/TEM_LIB
-$(EPOC32BUILD)/TEM_FINAL:: $(EPOC32BUILD)/TEM_BLD
-
-# Make engines with order only prerequisites should use them
-# other engines can use a simulation
-#
-ifneq ($(HAVE_ORDERONLY),)
-.PHONY:: $(EPOC32BUILD)/TEM_LIB
-
-$(EPOC32BUILD)/TEM_LIB:: $(EPOC32BUILD)/TEM_RESOURCE
-
-else
-# Set up some rules that will simulate order only behaviour on all
-# make engines:
-
-define predatedupdate
-	@touch --date='10 years ago' "$1"
-endef
-
-# This one is non-phony because it's the only one that 
-# anything actually depends upon in a purely incremental build.
-$(EPOC32BUILD)/TEM_LIB:: $(EPOC32BUILD)/TEM_RESOURCE
-	$(call predatedupdate,$@)
-endif
-
-# Optionally include user configuration if it exists.
--include $(FLMHOME)/user/default.flm
+# 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:
+# config/default.flm
+# Default build-configuration-wide rules and dependencies.
+# 
+#
+
+# put things in here that depend on EPOCROOT and 
+# therefore cannot go in globals.mk
+
+# metaflm depends on variables set in the configuration
+include $(FLMHOME)/metaflm.mk
+
+# TEM dependencies
+EPOC32BUILD:=$(EPOCROOT)/epoc32/build
+
+.PHONY:: $(EPOC32BUILD)/TEM_MAKMAKE
+.PHONY:: $(EPOC32BUILD)/TEM_RESOURCE
+.PHONY:: $(EPOC32BUILD)/TEM_BLD
+.PHONY:: $(EPOC32BUILD)/TEM_FINAL
+
+$(EPOC32BUILD)/TEM_MAKMAKE:: EXPORT
+$(EPOC32BUILD)/TEM_RESOURCE:: $(EPOC32BUILD)/TEM_MAKMAKE
+$(EPOC32BUILD)/TEM_BLD:: $(EPOC32BUILD)/TEM_LIB
+$(EPOC32BUILD)/TEM_FINAL:: $(EPOC32BUILD)/TEM_BLD
+
+# Make engines with order only prerequisites should use them
+# other engines can use a simulation
+#
+ifneq ($(HAVE_ORDERONLY),)
+.PHONY:: $(EPOC32BUILD)/TEM_LIB
+
+$(EPOC32BUILD)/TEM_LIB:: $(EPOC32BUILD)/TEM_RESOURCE
+
+else
+# Set up some rules that will simulate order only behaviour on all
+# make engines:
+
+define predatedupdate
+	@touch --date='10 years ago' "$1"
+endef
+
+# This one is non-phony because it's the only one that 
+# anything actually depends upon in a purely incremental build.
+$(EPOC32BUILD)/TEM_LIB:: $(EPOC32BUILD)/TEM_RESOURCE
+	$(call predatedupdate,$@)
+endif
+
+# Optionally include user configuration if it exists.
+-include $(FLMHOME)/user/default.flm
--- a/sbsv2/raptor/lib/flm/converged-comms/createcommdbs.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/converged-comms/createcommdbs.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,60 +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:
-#
-
-# FLM to build CommDB databases using CED.
-
-DBDONE:=$(EPOCBLD)/CommDb_$(PLATFORM)_$(CFG).done
-$(call makepathfor,$(DBDONE))
-
-# remember the name of the .done file so that we can make the FINAL stage of
-# installdefaultcommdb.flm depend on it
-CommDb_$(PLATFORM)_$(CFG)_done:=$(DBDONE)
-
-# macro for all the rules
-define createcommdbs
-
-FINAL:: $(DBDONE)
-
-$(DBDONE): TARGET
-	$(call startrule,createcommdbs) \
-	$(PERL) $(EXTENSION_ROOT)/createcommdbs.pl --command=build --platform=$(PLATFORM) --variant=$(CFG) --sourceDir=$(EXTENSION_ROOT)/$(SRCDIR) --platsec && \
-	touch $(DBDONE) \
-	$(call endrule,createcommdbs)
-
-CLEAN:: 
-	$(call startrule,clean) \
-	$(PERL) $(EXTENSION_ROOT)/createcommdbs.pl --command=clean --platform=$(PLATFORM) --variant=$(CFG) --sourceDir=$(EXTENSION_ROOT)/$(SRCDIR) --platsec && \
-	rm -f $(DBDONE) \
-	$(call endrule,clean)
-
-RELEASABLES:: 
-	@$(PERL) $(EXTENSION_ROOT)/createcommdbs.pl --command=releasables --platform=$(PLATFORM) --variant=$(CFG) --sourceDir=$(EXTENSION_ROOT)/$(SRCDIR) --platsec
-
-ifeq ($(WHATLOG),TRUE)
-FINAL::
-	@ { echo "<whatlog bldinf='$(COMPONENT_META)' mmp='' config='$(SBS_CONFIGURATION)'>" ; \
-	$(PERL) $(EXTENSION_ROOT)/createcommdbs.pl --command=releasables --platform=$(PLATFORM) --variant=$(CFG) --sourceDir=$(EXTENSION_ROOT)/$(SRCDIR) --platsec | \
-	(read -r LINE; while [ $$$$? -eq 0 ]; do \
-	echo "<build>$$$$LINE</build>"; \
-	read -r LINE; done; ); \
-	echo "</whatlog>"; } \
-	$(if $(DESCRAMBLE),2>&1 | $(DESCRAMBLE))
-endif
-
-endef
-
-# expand
-$(eval $(createcommdbs))
-
+# 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:
+#
+
+# FLM to build CommDB databases using CED.
+
+DBDONE:=$(EPOCBLD)/CommDb_$(PLATFORM)_$(CFG).done
+$(call makepathfor,$(DBDONE))
+
+# remember the name of the .done file so that we can make the FINAL stage of
+# installdefaultcommdb.flm depend on it
+CommDb_$(PLATFORM)_$(CFG)_done:=$(DBDONE)
+
+# macro for all the rules
+define createcommdbs
+
+FINAL:: $(DBDONE)
+
+$(DBDONE): TARGET
+	$(call startrule,createcommdbs) \
+	$(PERL) $(EXTENSION_ROOT)/createcommdbs.pl --command=build --platform=$(PLATFORM) --variant=$(CFG) --sourceDir=$(EXTENSION_ROOT)/$(SRCDIR) --platsec && \
+	touch $(DBDONE) \
+	$(call endrule,createcommdbs)
+
+CLEAN:: 
+	$(call startrule,clean) \
+	$(PERL) $(EXTENSION_ROOT)/createcommdbs.pl --command=clean --platform=$(PLATFORM) --variant=$(CFG) --sourceDir=$(EXTENSION_ROOT)/$(SRCDIR) --platsec && \
+	rm -f $(DBDONE) \
+	$(call endrule,clean)
+
+RELEASABLES:: 
+	@$(PERL) $(EXTENSION_ROOT)/createcommdbs.pl --command=releasables --platform=$(PLATFORM) --variant=$(CFG) --sourceDir=$(EXTENSION_ROOT)/$(SRCDIR) --platsec
+
+ifeq ($(WHATLOG),TRUE)
+FINAL::
+	@ { echo "<whatlog bldinf='$(COMPONENT_META)' mmp='' config='$(SBS_CONFIGURATION)'>" ; \
+	$(PERL) $(EXTENSION_ROOT)/createcommdbs.pl --command=releasables --platform=$(PLATFORM) --variant=$(CFG) --sourceDir=$(EXTENSION_ROOT)/$(SRCDIR) --platsec | \
+	(read -r LINE; while [ $$$$? -eq 0 ]; do \
+	echo "<build>$$$$LINE</build>"; \
+	read -r LINE; done; ); \
+	echo "</whatlog>"; } \
+	$(if $(DESCRAMBLE),2>&1 | $(DESCRAMBLE))
+endif
+
+endef
+
+# expand
+$(eval $(createcommdbs))
+
--- a/sbsv2/raptor/lib/flm/converged-comms/installdefaultcommdb.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/converged-comms/installdefaultcommdb.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,49 +1,49 @@
-# 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:
-#
-
-# FLM to install CommDB databases created using CED.
-
-# macro for all the rules
-define installdefaultcommdb
-
-FINAL:: $(CommDb_$(PLATFORM)_$(CFG)_done)
-	$(call startrule,installdefaultcommdb) \
-	$(PERL) $(EXTENSION_ROOT)/installdefaultcommdb.pl --command=build --platform=$(PLATFORM) --variant=$(CFG) --platsec \
-	$(call endrule,installdefaultcommdb)
-
-CLEAN:: 
-	$(call startrule,clean) \
-	$(PERL) $(EXTENSION_ROOT)/installdefaultcommdb.pl --command=clean --platform=$(PLATFORM) --variant=$(CFG) --platsec \
-	$(call endrule,clean)
-
-RELEASABLES::
-	@$(PERL) $(EXTENSION_ROOT)/installdefaultcommdb.pl --command=releasables --platform=$(PLATFORM) --variant=$(CFG) --platsec
-
-ifeq ($(WHATLOG),TRUE)
-FINAL::
-	@ { echo "<whatlog bldinf='$(COMPONENT_META)' mmp='' config='$(SBS_CONFIGURATION)'>" ; \
-	$(PERL) $(EXTENSION_ROOT)/installdefaultcommdb.pl --command=releasables --platform=$(PLATFORM) --variant=$(CFG) --platsec | \
-	(read -r LINE; while [ $$$$? -eq 0 ]; do \
-	echo "<build>$$$$LINE</build>"; \
-	read -r LINE; done; ); \
-	echo "</whatlog>"; } \
-	$(if $(DESCRAMBLE),2>&1 | $(DESCRAMBLE))
-endif
-
-endef
-
-# expand
-$(eval $(installdefaultcommdb))
-
+# 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:
+#
+
+# FLM to install CommDB databases created using CED.
+
+# macro for all the rules
+define installdefaultcommdb
+
+FINAL:: $(CommDb_$(PLATFORM)_$(CFG)_done)
+	$(call startrule,installdefaultcommdb) \
+	$(PERL) $(EXTENSION_ROOT)/installdefaultcommdb.pl --command=build --platform=$(PLATFORM) --variant=$(CFG) --platsec \
+	$(call endrule,installdefaultcommdb)
+
+CLEAN:: 
+	$(call startrule,clean) \
+	$(PERL) $(EXTENSION_ROOT)/installdefaultcommdb.pl --command=clean --platform=$(PLATFORM) --variant=$(CFG) --platsec \
+	$(call endrule,clean)
+
+RELEASABLES::
+	@$(PERL) $(EXTENSION_ROOT)/installdefaultcommdb.pl --command=releasables --platform=$(PLATFORM) --variant=$(CFG) --platsec
+
+ifeq ($(WHATLOG),TRUE)
+FINAL::
+	@ { echo "<whatlog bldinf='$(COMPONENT_META)' mmp='' config='$(SBS_CONFIGURATION)'>" ; \
+	$(PERL) $(EXTENSION_ROOT)/installdefaultcommdb.pl --command=releasables --platform=$(PLATFORM) --variant=$(CFG) --platsec | \
+	(read -r LINE; while [ $$$$? -eq 0 ]; do \
+	echo "<build>$$$$LINE</build>"; \
+	read -r LINE; done; ); \
+	echo "</whatlog>"; } \
+	$(if $(DESCRAMBLE),2>&1 | $(DESCRAMBLE))
+endif
+
+endef
+
+# expand
+$(eval $(installdefaultcommdb))
+
--- a/sbsv2/raptor/lib/flm/e32abiv2.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,1178 +1,1277 @@
-# 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:
-# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
-# Knows how to build all possible ABIV2 executables for ARM
-#
-#
-
-# Only build feature invariant binaries in non-product builds *and*
-# Only build feature variant binaries in product builds.
-#
-# FEATUREVARIANTNAME != "" implies product build
-# FEATUREVARIANT == 1 implies a feature variant binary
-#
-# test FEATUREVARIANTNAME=="" or FEATUREVARIANT==1
-#
-ifneq ($(or $(call equal,$(FEATUREVARIANTNAME),),$(call equal,$(FEATUREVARIANT),1)),)
-
-$(if $(FLMDEBUG),$(info <flm name='e32abiv2' target='$(TARGET)' type='$(TARGETTYPE)' outputpath='$(OUTPUTPATH)' metasource='$(METASOURCE)' postlinkfiletype='$(POSTLINKFILETYPE)' />))
-
-# Strip switch-type parameters
-#
-POSTLINKTARGETTYPE:=$(strip $(POSTLINKTARGETTYPE))
-UID1:=$(strip $(UID1))
-UID2:=$(strip $(UID2))
-UID3:=$(strip $(UID3))
-SID:=$(strip $(SECUREID))
-VENDORID:=$(strip $(VENDORID))
-AUTOEXPORTS:=$(strip $(AUTOEXPORTS))
-DEFFILE:=$(strip $(DEFFILE))
-IMPORTLIBRARYREQUIRED:=$(strip $(IMPORTLIBRARYREQUIRED))
-EPOCALLOWDLLDATA:=$(strip $(EPOCALLOWDLLDATA))
-PAGED:=$(strip $(PAGED))
-
-# the output directories
-VARIANTPLATFORM:=$(VARIANTPLATFORM)$(FEATUREVARIANTNAME)
-RELEASABLEPATH:=$(RELEASEPATH)/$(VARIANTPLATFORM)/$(VARIANTTYPE)
-INTERMEDIATEPATH:=$(OUTPUTPATH)/$(VARIANTPLATFORM)/$(VARIANTTYPE)
-INTERMEDIATE_PLATFORM_PATH:=$(OUTPUTPATH)/$(VARIANTPLATFORM)
-TRACE_MARKER_PATH:=$(OUTPUTPATH)
-IMPORTLIBPATH:=$(RUNTIME_LIBS_PATH)
-
-# LOCALLY USED VARIABLES
-CLEANTARGETS:=
-WHATRELEASE:=
-
-# Work out which new/delete library to use for binaries.
-CHECKLIB_TYPE:=symc++
-STDCPPTAGFILE:=
-ifeq ($(NOSTDCPP),1)
-  ifeq ($(STDCPP),1)
-    $(info <warning>STDCPP and NOSTDCPP both specified in $(PROJECT_META)</warning>)
-  else
-    ifeq ($(HAS_DEDICATED_OP_NEWDEL_LIB),1)
-      DEFAULT_NEWLIB:=$(DEFAULT_SYMBIAN_NEWLIB)
-    endif
-  endif
-else
-  ifeq ($(STDCPP),1)
-    CDEFS:=$(CDEFS) __SYMBIAN_STDCPP_SUPPORT__
-    ifneq ($(SUPPORTS_STDCPP_NEWLIB),)
-      ifeq ($(HAS_DEDICATED_OP_NEWDEL_LIB),1)
-        DEFAULT_NEWLIB:=$(DEFAULT_STDCPP_NEWLIB)
-      endif
-      CHECKLIB_TYPE:=stdc++
-      STDCPPTAGFILE:=$(EPOCROOT)/epoc32/tools/tag/tag_elf
-    endif
-  endif
-endif
-
-# If NEWLIB is specified in the MMP file, it overrides all the past stuff.
-ifeq ($(NEWLIB),)
-  NEWLIB:=$(DEFAULT_NEWLIB)
-endif
-
-
-##########################################################################
-## OUTPUTS - externally relevant targets that this FLM generates
-
-
-ifeq ($(EXPORTLIBRARY),)
-  EXPORTLIBRARY:=$(TARGET)
-endif
-
-# This will insert the file version between the name and the extension.
-# If there is more than one dot in generated filename the inserted position will be
-# BEFORE the last but two dot. E.g name1.name2.name3.dll to name1.name2{version}.name3.dll
-LIBEXT:=$(lastword $(subst .,$(CHAR_SPACE) ,$(EXPORTLIBRARY)))
-LIBBASE:=$(patsubst %.$(LIBEXT),%,$(EXPORTLIBRARY))
-ifneq ($(findstring .,$(EXPORTLIBRARY)),)
-  # Please note $(EXPORTLIBRARY) doesn't include target type.
-  VER_E32IMPORTLIBBASE:=$(IMPORTLIBPATH)/$(LIBBASE){$(VERSIONHEX)}.$(LIBEXT)
-else
-  VER_E32IMPORTLIBBASE:=$(IMPORTLIBPATH)/$(EXPORTLIBRARY){$(VERSIONHEX)}
-endif
-
-# Postlinkable targets need to be linked and elf2e32'd
-ifneq ($(DOPOSTLINK),)
-    E32TARGET:=$(RELEASABLEPATH)/$(TARGET)$(if $(EXPLICITVERSION),{$(VERSIONHEX)},).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(POSTLINKFILETYPE))
-    LINK_TARGET:=$(RELEASABLEPATH)/$(TARGET)$(if $(EXPLICITVERSION),{$(VERSIONHEX)},).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(POSTLINKFILETYPE)).sym
-    MAPFILE:=$(RELEASABLEPATH)/$(TARGET).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(POSTLINKFILETYPE)).map
-else
-  E32TARGET:=
-  LINK_TARGET:=
-  MAPFILE:=
-endif
-
-# libs and klibs, on the other hand need to be archived
-ifneq ($(call isoneof,$(TARGETTYPE),lib klib stdlib),)
-  ARTARGET:=$(RELEASABLEPATH)/$(TARGET).lib
-  # We need libs and klibs before we can link stuff with them:
-  LIBRARY:: $(ARTARGET)
-else
-  ARTARGET:=
-endif
-
-
-ifneq ($(IMPORTLIBRARYREQUIRED),) # no dso files for plugins, animation dlls etc
-  # make sure we don't build import libraries more than once for UDEB and UREL
-  # Without this, wierd target-specific variable problems happen with LIBRARY in particular
-
-  TMP_IMPORTLIBTARGET_ROOT:=$(IMPORTLIBPATH)/$(EXPORTLIBRARY)
-
-  # ABIv2 .dso
-  IMPORTLIBTARGET_DSO:=
-  IMPORTLIBTARGETVERSIONED_DSO:=
-
-  BUILDMARKER_IMPORTLIBTARGET_DSO:=TARGET_$(subst :,,$(VER_E32IMPORTLIBBASE)).dso
-  WHATRELEASE:=$(WHATRELEASE) $(if $(EXPLICITVERSION),,$(TMP_IMPORTLIBTARGET_ROOT).dso)
-  WHATRELEASE:=$(WHATRELEASE) $(VER_E32IMPORTLIBBASE).dso
-  ifeq ($($(BUILDMARKER_IMPORTLIBTARGET_DSO)),)
-    IMPORTLIBTARGET_DSO:=$(TMP_IMPORTLIBTARGET_ROOT).dso
-    IMPORTLIBTARGETVERSIONED_DSO:=$(VER_E32IMPORTLIBBASE).dso
-    $(eval $(BUILDMARKER_IMPORTLIBTARGET_DSO):=1)
-  endif
-
-  # ABIv1 .lib (for specific builds, toolchains and host OS platforms only)
-  IMPORTLIBTARGET_LIB:=
-  IMPORTLIBTARGETVERSIONED_LIB:=
-  BUILDMARKER_IMPORTLIBTARGET_LIB:=TARGET_$(subst :,,$(VER_E32IMPORTLIBBASE)).lib
-  # Only for builds that require and support them, and only on windows
-  ifeq ($(OSTYPE),cygwin)
-  ifeq ($(GENERATE_ABIV1_IMPLIBS),1)
-    WHATRELEASE:=$(WHATRELEASE) $(if $(EXPLICITVERSION),,$(TMP_IMPORTLIBTARGET_ROOT).lib)
-    WHATRELEASE:=$(WHATRELEASE) $(VER_E32IMPORTLIBBASE).lib
-    ifeq ($($(BUILDMARKER_IMPORTLIBTARGET_LIB)),)
-      IMPORTLIBTARGET_LIB:=$(TMP_IMPORTLIBTARGET_ROOT).lib
-      IMPORTLIBTARGETVERSIONED_LIB:=$(VER_E32IMPORTLIBBASE).lib
-      $(eval $(BUILDMARKER_IMPORTLIBTARGET_LIB):=1)
-    endif
-  endif
-  endif
-endif
-
-# Try to make sure that we get the right linkas name
-# If linkas is specified then split it up and
-# put the hex version number in the right place
-ifeq ($(LINKAS),)
-  LINKASNAME=$(TARGET)
-  LINKASTYPE=$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(POSTLINKFILETYPE))
-else
-  SPLIT_LINKAS=$(subst ., ,$(LINKAS))
-  LINKASNAME=$(word 1,$(SPLIT_LINKAS))
-  LINKASTYPE=$(word 2,$(SPLIT_LINKAS))
-endif
-
-# ignore UID3 if it is zero
-ifeq ($(UID3),00000000)
-  LINKASVERSIONED=$(LINKASNAME){$(VERSIONHEX)}.$(LINKASTYPE)
-else
-  LINKASVERSIONED=$(LINKASNAME){$(VERSIONHEX)}$(if $(UID3),[$(UID3)],).$(LINKASTYPE)
-endif
-
-##########################################################################
-## TARGET GROUPS ##
-RELEASABLES:=$(strip $(E32TARGET) $(ARTARGET) $(LINK_TARGET) $(MAPFILE))
-# More targets to be added later
-TARGETS:=$(strip $(E32TARGET) $(IMPORTLIBTARGET) $(LINK_TARGET) $(ARTARGET))
-
-CREATABLEPATHS:=$(OUTPUTPATH)
-CREATABLEPATHS:=$(CREATABLEPATHS) $(INTERMEDIATE_PLATFORM_PATH)
-CREATABLEPATHS:=$(CREATABLEPATHS) $(INTERMEDIATEPATH)
-CREATABLEPATHS:=$(CREATABLEPATHS) $(RELEASABLEPATH)
-CREATABLEPATHS:=$(CREATABLEPATHS) $(RUNTIME_LIBS_PATH)
-CREATABLEPATHS:=$(CREATABLEPATHS) $(IMPORTLIBPATH)
-WHATRELEASE:=$(WHATRELEASE) $(RELEASABLES)
-
-
-
-## HIGH LEVEL Targets ##
-.PHONY:: $(ALLTARGET)
-
-## GLOBAL TARGETS ############################################################
-$(ALLTARGET):: $(RELEASABLES)
-TARGET:: $(RELEASABLES)
-
-## Internal targets ##
-
-# Determine the name of the generated DSO file ###############################
-# This is to generate the dso with the Some{Versionhex}.file.dso
-# It reproduces what appears to be a problem in the current build system
-# that affects messageintercept{000a0000}.esockdebug.dso whose
-# filename differs from it's "linkas" name.
-E32VAR:=$(subst .,$(CHAR_SPACE) ,$(TARGET))
-E32SOME:=$(word 1,$(E32VAR))
-E32VAR2:=$(patsubst $(E32SOME).%,%,$(TARGET))
-
-# Separate '_SH' variables created for output into bash - Preserves '{' and '}'
-
-ifneq ($(findstring .,$(TARGET)),)
-	DSODEFFILENAMEBASE:=$(E32SOME){$(VERSIONHEX)}.$(E32VAR2)
-else
-	DSODEFFILENAMEBASE:=$(TARGET){$(VERSIONHEX)}
-endif
-GENERATED_DSO:=$(call dblquote,$(INTERMEDIATEPATH)/$(DSODEFFILENAMEBASE).dso)
-GENERATED_DEFFILE:=$(call dblquote,$(INTERMEDIATEPATH)/$(DSODEFFILENAMEBASE).def)
-
-## IMPORT LIBRARY  ###########################################################
-
-# Static libraries will be postlinked when they are used so don't try to postlink them
-
-ifneq ($(IMPORTLIBRARYREQUIRED),)
-ifneq ($(or $(DEFFILE),$(EXPORTUNFROZEN)),)
-# Both ABIv2 .dso and ABIv1 .lib import library generation require a processed .def file,
-# unless EXPORTUNFROZEN is being used
-PREPPEDDEFFILE:=
-ifneq ($(DEFFILE),)
-  ifeq ($(EXPORTUNFROZEN),)
-    PREPPEDDEFFILE:=$(INTERMEDIATEPATH)/$(TARGET).prep
-    CLEANTARGETS:=$(CLEANTARGETS) $(PREPPEDDEFFILE)
-    define importlibtarget_prepfile
-      $(PREPPEDDEFFILE): $(DEFFILE)
-		$(call startrule,importlibtarget_prepfile,FORCESUCCESS) \
-		$(PREPDEF) $(call dblquote,$(DEFFILE)) $(call dblquote,$(PREPPEDDEFFILE)) \
-		$(call endrule,importlibtarget_prepfile)
-    endef
-    $(eval $(importlibtarget_prepfile))
-  endif
-endif
-
-# ABIv2 .dso
-ifneq ($(IMPORTLIBTARGET_DSO),) # check that we haven't tried to specify this target already
-
-  ifneq ($(EXPLICITVERSION),)
-    TARGETS:=$(strip $(TARGETS) $(IMPORTLIBTARGETVERSIONED_DSO))
-
-    # Add this importlibrary to our global targets
-    LIBRARY:: $(IMPORTLIBTARGETVERSIONED_DSO)
-    $(ALLTARGET):: $(IMPORTLIBTARGETVERSIONED_DSO)
-    TARGET:: $(IMPORTLIBTARGETVERSIONED_DSO)
-
-  else
-    TARGETS:=$(strip $(TARGETS) $(IMPORTLIBTARGETVERSIONED_DSO) $(IMPORTLIBTARGET_DSO))
-
-    # Add this importlibrary to our global targets
-    LIBRARY:: $(IMPORTLIBTARGET_DSO)
-    $(ALLTARGET):: $(IMPORTLIBTARGETVERSIONED_DSO) $(IMPORTLIBTARGET_DSO)
-    TARGET:: $(IMPORTLIBTARGETVERSIONED_DSO) $(IMPORTLIBTARGET_DSO)
-
-
-  endif
-
-
-
-  ifneq ($(EXPORTUNFROZEN),) # Unfrozen  - warn and create .dso as side-effect of the final postlink
-    $(info <warning project='$(PROJECT_META)' component='$(COMPONENT_META)'>EXPORTUNFROZEN present in $(PROJECT_META) - unfrozen exports will be represented in import library.</warning> )
-    define importlibtarget_unfrozen
-      $(IMPORTLIBTARGET_DSO): $(IMPORTLIBTARGETVERSIONED_DSO)
-		$(call startrule,importlibtarget_unfrozen,FORCESUCCESS) \
-		$(GNUCP) $$(call dblquote,$$<) $$(call dblquote,$$@) \
-		$(call endrule,importlibtarget_unfrozen)
-
-       CLEANTARGETS:=$$(CLEANTARGETS) $(IMPORTLIBTARGET_DSO)
-
-    endef
-
-    define importlibtarget_unfrozen_ver
-      $(IMPORTLIBTARGETVERSIONED_DSO): $(E32TARGET)
-		$(call startrule,importlibversioned_unfrozen,FORCESUCCESS) \
-		$(GNUCP) "$(GENERATED_DSO)" "$$@" \
-		$(call endrule,importlibversioned_unfrozen)
-
-      CLEANTARGETS:=$$(CLEANTARGETS) $(IMPORTLIBTARGET_DSO)
-    endef
-
-    ifeq ($(EXPLICITVERSION),)
-      # Generate the general dso if we aren't
-      # being asked to make just the specific version.
-      $(eval $(importlibtarget_unfrozen))
-    endif
-
-    $(eval $(importlibtarget_unfrozen_ver))
-  else
-    ifneq ($(DEFFILE),) # Frozen - use the def file and create .dso directly
-      define importlibtarget_func
-       $(IMPORTLIBTARGET_DSO): $(IMPORTLIBTARGETVERSIONED_DSO)
-	   $(call startrule,importlibtarget,FORCESUCCESS) \
-	   $(GNUCP) "$$<" "$$@" \
-	   $(call endrule,importlibtarget)
-
-          CLEANTARGETS:=$$(CLEANTARGETS) $(IMPORTLIBTARGET_DSO)
-      endef
-
-      ifeq ($(EXPLICITVERSION),)
-          # Generate the general dso if we aren't
-          # being asked to make just the specific version.
-          $(eval $(importlibtarget_func))
-      endif
-
-      define importlibtargetversioned_func
-        $(IMPORTLIBTARGETVERSIONED_DSO): $(ELF2E32) $(PREPPEDDEFFILE)
-	      $(call startrule,importlibversioned,FORCESUCCESS) \
-	      $(ELF2E32) --sid=0x$(if $(SID),$(SID),$(if $(UID3),$(UID3),0))  --version=$(VERSION)  	   \
-	 	  --definput="$(PREPPEDDEFFILE)" 				   \
-	 	  --dso=$$(call dblquote,$$@) 				   \
-	 	  --linkas=$(call dblquote,$(LINKASVERSIONED)) \
-	      $(call endrule,importlibversioned)
-
-              CLEANTARGETS:=$$(CLEANTARGETS) $(IMPORTLIBTARGETVERSIONED_DSO)
-      endef
-      $(eval $(importlibtargetversioned_func))
-    endif #  ifneq ($(DEFFILE),)
-  endif #  ifneq ($(EXPORTUNFROZEN),)
-endif #  ifneq ($(IMPORTLIBTARGET_DSO),)
-
-# ABIv1 .lib
-ifneq ($(IMPORTLIBTARGETVERSIONED_LIB),) # check that we haven't tried to specify this target already
-  CLEANTARGETS:=$(CLEANTARGETS) $(IMPORTLIBTARGETVERSIONED_LIB) $(IMPORTLIBTARGET_LIB)
-
-  define abiv1_generatelib
-
-    ifeq ($(EXPLICITVERSION),)
-      LIBRARY:: $(IMPORTLIBTARGETVERSIONED_LIB) $(IMPORTLIBTARGET_LIB)
-
-    else
-      LIBRARY:: $(IMPORTLIBTARGETVERSIONED_LIB)
-
-    endif
-
-    # If frozen, a prepped .def file is used as the basis for .lib creation
-    # If unfrozen, .lib files are based on the .def file generated by the final postlink
-    $(IMPORTLIBTARGETVERSIONED_LIB): $(if $(EXPORTUNFROZEN),$(E32TARGET),$(PREPPEDDEFFILE))
-	$(call startrule,importlibversioned_abiv1) \
-        if [ -f "$(EPOCROOT)/epoc32/tools/def2dll.pl" -a -f "$(if $(EXPORTUNFROZEN),$(GENERATED_DEFFILE),$(PREPPEDDEFFILE))" ]; then \
-                 $(PERL) $(EPOCROOT)/epoc32/tools/def2dll.pl \
-		--path=$(IMPORTLIBPATH) \
-		--bldpath=$(INTERMEDIATEPATH) \
-		--import=$(notdir $(basename $(IMPORTLIBTARGETVERSIONED_LIB))) \
-		--deffile="$(if $(EXPORTUNFROZEN),$(GENERATED_DEFFILE),$(PREPPEDDEFFILE))" \
-		--linkAs=$(call dblquote,$(LINKASVERSIONED)) \
-		--inter ; fi \
-	$(call endrule,importlibversioned_abiv1)
-
-    ifeq ($(EXPLICITVERSION),)
-      $(IMPORTLIBTARGET_LIB): $(IMPORTLIBTARGETVERSIONED_LIB)
-	$(call startrule,importlibtarget_abiv1) \
-	if [ -f $(EPOCROOT)/epoc32/tools/def2dll.pl ]; then $(GNUCP) "$$<" "$$@" ; fi \
-	$(call endrule,importlibtarget_abiv1)
-    endif
-  endef
-
-  $(eval $(abiv1_generatelib))
-endif #  ifneq ($(IMPORTLIBTARGET_LIB),)
-endif #  ($(or $(DEFFILE),$(EXPORTUNFROZEN)),)
-endif #  ifneq ($(IMPORTLIBRARYREQUIRED),)
-
-
-## POSTLINK ##################################################################
-
-# Set up the name of the exports file if this is a customdll
-EXPTARGET:=
-ifneq ($(DOPOSTLINK),)
-  ifneq ($(and $(or $(STATICLIBRARY),$(ARMLIBS),$(ARMRT)),$(DEFFILE)),)
-    EXPTARGET:=$(INTERMEDIATE_PLATFORM_PATH)/$(notdir $(VER_E32IMPORTLIBBASE)).exp
-  endif
-endif
-
-# Generating the import library is enough if TARGETTYPE=implib #############
-
-ifneq ($(DOPOSTLINK),)
-include $(FLMHOME)/e32postlink.mk
-endif # ifneq ($(DOPOSTLINK),)
-
-ifneq ($(TARGETTYPE),implib)
-
-## CUSTOM DLLS ###############################################################
-# exp file
-#
-# This tends to help getting exported objects
-# out of the arm libs and into custom dlls.
-
-ifneq ($(EXPTARGET),)
-ifeq ($(TARGET_$(EXPTARGET)),)
-# We only need one of these exptargets for UDEB and UREL
-TARGET_$(EXPTARGET):=1
-
-EXPTARGETASMFILE:=$(INTERMEDIATE_PLATFORM_PATH)/$(notdir $(VER_E32IMPORTLIBBASE)).s
-
-define e32expgen_func
-$(EXPTARGET): $(DEFFILE) $(ELF2E32)
-	$(call startrule,expgen) \
-	$(ELF2E32) \
-	   --definput=$$(call dblquote,$(DEFFILE)) \
-	   --dump=a \
-	   --output=$(call dblquote,$(EXPTARGETASMFILE)) && \
-	$(ASM) $(TARGET_ARCH_OPTION) $(AAPCS_OPTION) $(ASM_OUTPUT_OPTION) $$(call dblquote, $$@) $(EXPTARGETASMFILE) \
-	$(call endrule,expgen)
-endef
-
-$(eval $(e32expgen_func))
-CLEANTARGETS:=$(CLEANTARGETS) $(EXPTARGET) $(EXPTARGETASMFILE)
-endif
-endif
-
-
-
-
-## SOURCE FILES ##############################################################
-
-# Source files can be either C++ files (.cpp) or Assmbler-in-C++ files (.cia)
-# We have to split the two because they have the same link stage, the compile
-# stage is different for each.
-
-CPPFILEEXTENSIONS:=.cpp .CPP .Cpp .CPp .CpP .cPP .cpP .cPp .cc .CC \
-	.Cc .c++ .C++ .cxx .CXX .Cxx .cXx .CxX .CXx .cC .cXX .cxX
-CFILEEXTENSIONS:=.c .C
-CIAFILEEXTENSIONS:=.CIA .cia .Cia .cIa .cIA .ciA .CIa .CiA
-ASMFILEEXTENSIONS:=.s .S
-
-
-# Extract the CPP files from our sources
-CPPFILES:=$(call extractfilesoftype,$(CPPFILEEXTENSIONS),$(SOURCE))
-CFILES:=$(call extractfilesoftype,$(CFILEEXTENSIONS),$(SOURCE))
-ASMFILES:=$(call extractfilesoftype,$(ASMFILEEXTENSIONS),$(SOURCE))
-
-# Find out what assember-in-c files there are
-# If appropriate, work out what CPP files will be created from the assembler files
-CIAFILES:=$(call extractfilesoftype,$(CIAFILEEXTENSIONS),$(SOURCE))
-CIA_CPPFILES:=
-ifeq ($(TRANSFORM_CIA),1)
-  CIA_CPPFILES:=$(call relocatefiles,$(INTERMEDIATEPATH),$(call extractandmap,$(CIAFILEEXTENSIONS),_.cpp,$(CIAFILES)))
-else
-
-endif
-
-## LINK ######################################################################
-# Bring together all the .o files compiled from  .cpp, .c, .s and .cia files.
-# These files are stored in the "non-releasable" output diretory.
-
-define mapcpp2object
-$(call relocatefiles,$(INTERMEDIATEPATH),$(call extractandmap,$(CPPFILEEXTENSIONS),.o,$1))
-endef
-
-define mapc2object
-$(call relocatefiles,$(INTERMEDIATEPATH),$(call extractandmap,$(CFILEEXTENSIONS),.o,$1))
-endef
-
-define mapasm2object
-$(call relocatefiles,$(INTERMEDIATEPATH),$(call extractandmap,$(ASMFILEEXTENSIONS),.o,$1))
-endef
-
-define mapcia2object
-$(call relocatefiles,$(INTERMEDIATEPATH),$(call extractandmap,$(CIAFILEEXTENSIONS),_.o,$1))
-endef
-
-# Determine what object files will be linked by using the source files.
-CPPFILES_LINKOBJECTS:=$(call mapcpp2object,$(CPPFILES))
-CFILES_LINKOBJECTS:=$(call mapc2object,$(CFILES))
-ifeq ($(TRANSFORM_CIA),1) 
-  CIAFILES_LINKOBJECTS:=$(patsubst %_.cpp,%_.o,$(CIA_CPPFILES))
-else
-  CIAFILES_LINKOBJECTS:=$(call mapcia2object,$(CIAFILES))
-endif
-ASMFILES_LINKOBJECTS:=$(call mapasm2object,$(ASMFILES))
-
-# Try to link object files in the order in which the source files were specified.
-# This makes BC comparisons with non-Raptor builds easier.
-# Use the order of the source list to establish the order of the object files:
-LINKOBJECTS:=$(call relocatefiles,$(INTERMEDIATEPATH),$(SOURCE))
-# Replace the file extensions of the Source files with .o (or _.o for cia files) now
-# the list will contain the object files in the same order as the list of source files.
-LINKOBJECTS:=$(foreach FILE,$(LINKOBJECTS),$(basename $(FILE))$(if $(filter $(addprefix %,$(CIAFILEEXTENSIONS)),$(FILE)),_).o)
-
-ifneq ($(MULTIFILE_ENABLED),)
-MULTIFILEOBJECT:=$(INTERMEDIATEPATH)/$(TARGET).$(POSTLINKFILETYPE)_$(VARIANTTYPE)_multifileobject.o
-MULTIFILE_VIAFILE:=$(INTERMEDIATEPATH)/$(TARGET)_$(VARIANTTYPE)_multifile.via
-endif
-
-## Via file ####################################
-# list of all objects to be linked
-#
-VIAFILE:=$(INTERMEDIATEPATH)/$(TARGET)_$(VARIANTTYPE)_objects.via
-ifneq ($(GENERATELINKERFEEDBACK),)
-FEEDBACKFILE:=$(INTERMEDIATEPATH)/$(TARGET)_$(VARIANTTYPE)_feedback.fdb
-endif
-
-# The groupin10 macro allows us to construct a via file, 10 objects at a time
-# to avoid limits on argument lengths and sizes on Windows.
-# It expands to a list of commands, each of which is on a separate line.
-# This causes the shell to be invoked once for each line but each line should
-# be shorter than the maximum allowed by windows.
-define groupin10
-	$(if $1,@echo -e $(foreach L,$(wordlist 1,10,$1),"$(L)\\n") >>$(VIAFILE),)
-	$(if $1,$(call groupin10,$(wordlist 11,$(words $1),$1)),@true)
-endef
-
-################################################
-
-
-## Link-type selection:
-#	runtime static libraries link via AR
-ifneq ($(ARTARGET),)
-# Assuming that there are no libdeps in this case because this is probably one of the
-# Runtime libraries which has no deps.
-
-define artarget_func
-$(ARTARGET): $(if $(MULTIFILE_ENABLED),$(MULTIFILEOBJECT),$(LINKOBJECTS)) $(STDCPPTAGFILE)
-	$(if $(MULTIFILE_ENABLED),,@echo "$(STDCPPTAGFILE)" > $(VIAFILE);
-	$(call groupin10,$(LINKOBJECTS)) ;)
-	$(call startrule,ar,FORCESUCCESS) \
-	$$(call dblquote,$(AR)) $(ARCHIVER_CREATE_OPTION) $$@ $(if $(MULTIFILE_ENABLED),$(MULTIFILEOBJECT),$(COMMANDFILE_OPTION)$(VIAFILE)) \
-	$(if $(DUMPBCINFO),&& $(FROMELF) -v $$@  > $$@.elfdump,)  \
-	$(call endrule,ar)
-endef
-$(eval $(artarget_func))
-
-CLEANTARGETS:=$(CLEANTARGETS) $(VIAFILE) $(ARTARGET) $(if $(DUMPBCINFO),$(ARTARGET).elfdump,)
-endif
-
-
-
-# Targettype is some type of DLL or EXE (or derivative)
-ifneq ($(LINK_TARGET),)
-
-escaped_located_ARMLIBS:=$(foreach L,$(ARMLIBS),$(call ruleEscape,$(wildcard $(subst $(CHAR_SPACE),?,$(RVCTLIB)/*/$(L)))))
-quoted_located_ARMLIBS:=$(foreach L,$(ARMLIBS),$(call dblquoteitem,$(wildcard $(RVCTLIB)/*/$(L))))
-located_STATICLIBRARIES:=$(foreach L,$(STATICLIBRARY),$(STATIC_LIBRARY_DIR)/$(L).lib)
-e32abiv2_LIBS:=$(EXPTARGET) $(LINKER_STUB_LIBRARY) $(if $(STATIC_RUNTIME_LIB),$(STATIC_RUNTIME_DIR)/$(STATIC_RUNTIME_LIB),) $(located_STATICLIBRARIES)
-# DLLS and EXEs - These objects are linked by a linker
-ifeq ($(ARMRT),)
-# Some of the runtime libraries do not set ARMRT because of a circular reference
-# problem; we need to stop these from linking to their own dso and not link to
-# the STATIC_LIBS_LIST.
-ifneq ($(findstring $(TARGET).dso,$(RUNTIME_LIBS_LIST)),)
-# (almost) ARM RUNTIME LIBS
-REDUCED_RUNTIME_LIBS_LIST:=$(subst $(TARGET).dso,,$(RUNTIME_LIBS_LIST))
-
-ifeq ($(VARIANTTYPE),udeb)
-  e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(IMPORTLIBPATH)/,$(LIBRARY_DEBUG)) $(addprefix $(RUNTIME_LIBS_PATH)/,$(REDUCED_RUNTIME_LIBS_LIST)) 
-else
-  e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(IMPORTLIBPATH)/,$(LIBRARY)) $(addprefix $(RUNTIME_LIBS_PATH)/,$(REDUCED_RUNTIME_LIBS_LIST)) 
-endif
-quoted_e32abiv2_LIBS=$(e32abiv2_LIBS) $(quoted_located_ARMLIBS)
-escaped_e32abiv2_LIBS=$(e32abiv2_LIBS) $(escaped_located_ARMLIBS)
-
-else
-# NORMAL
-#
-ifeq ($(VARIANTTYPE),udeb)
-  e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(IMPORTLIBPATH)/,$(LIBRARY_DEBUG))
-else
-  e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(IMPORTLIBPATH)/,$(LIBRARY))
-endif
-ifeq ($(HAS_DEDICATED_OP_NEWDEL_LIB),1)
-  e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(RUNTIME_LIBS_PATH)/,$(NEWLIB))
-endif
-quoted_e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(RUNTIME_LIBS_PATH)/,$(RUNTIME_LIBS_LIST)) $(call addquotedprefix,$(STATIC_LIBS_PATH)/,$(STATIC_LIBS_LIST)) $(quoted_located_ARMLIBS)
-escaped_e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(RUNTIME_LIBS_PATH)/,$(RUNTIME_LIBS_LIST)) $(addprefix $(call ruleEscape,$(STATIC_LIBS_PATH)/),$(STATIC_LIBS_LIST)) $(escaped_located_ARMLIBS)
-
-endif
-else
-# ARM RUNTIME LIBS
-ifeq ($(VARIANTTYPE),udeb)
-  e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(IMPORTLIBPATH)/,$(LIBRARY_DEBUG)) 
-else
-  e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(IMPORTLIBPATH)/,$(LIBRARY))
-endif
-quoted_e32abiv2_LIBS=$(e32abiv2_LIBS) $(quoted_located_ARMLIBS)
-escaped_e32abiv2_LIBS=$(e32abiv2_LIBS) $(escaped_located_ARMLIBS)
-endif
-
-# NOTE: the groupin10 macro must be used before a call to the "startrule" macro
-# because the code between startrule and endrule is packaged up into one
-# commandline which would defeat the purpose of groupin10.
-# This is undesirable because viafile generation commands appear
-# outside the relevant tags but it is also unavoidable.
-define linktarget_func
-## The actual link target, dependencies and build step
-$(LINK_TARGET): $(if $(MULTIFILE_ENABLED),$(MULTIFILEOBJECT) $(CIAFILES_LINKOBJECTS),$(LINKOBJECTS)) $(escaped_e32abiv2_LIBS) $(LINKER_ENTRYPOINT_LIBDEP) $(if $(SUPPORTS_STDCPP_NEWLIB),$(CHECKLIB)) $(if $(LINKERFEEDBACK_STAGE2),$(FEEDBACKFILE),)
-	$(if $(MULTIFILE_ENABLED),,@echo -n "" > $(VIAFILE);
-	$(call groupin10,$(LINKOBJECTS)) ;)
-	$(call startrule,link) \
-	$(if $(PERTURBSTARTTIME),$(RANSLEEP) $(PERTURBMSECS) ;,) \
-	$(if $(SUPPORTS_STDCPP_NEWLIB),$(if $(located_STATICLIBRARIES),$(CHECKLIB) $(CHECKLIB_TYPE) --elf $(call dblquote,$(located_STATICLIBRARIES)) &&,),) \
-	$(LD) $(LINKER_MISC_FLAGS) $(LINKER_DEFAULT_LIB_PATHS) $(SYMBIAN_LINK_FLAGS) $(if $(DEBUG_INFO),$(LINKER_DEBUG_OPTION),$(LINKER_NODEBUG_OPTION)) \
-	  $(SHARED_OBJECT_OPTION) $(SPLIT_OPTION) \
-	  $(RW_BASE_OPTION) 0x400000 \
-	  $(LINKER_ARCH_OPTION) \
-	  $(SYMVER_OPTION) $(SO_NAME_OPTION) $(call dblquote,$(LINKASVERSIONED)) \
-	  $(LINKER_ENTRYPOINT_SETTING) \
-	  -o $$(call dblquote,$$@) \
-	  $(if $(LTCG),$(LTCG_OPTION),) \
-	  $(LINKER_SYMBOLS_OPTION) $(LINKER_SYMBOLS_FILE_OPTION) \
-	  $(call dblquote,$(MAPFILE)) \
-  	  $(LINKEROPTION) \
-	  $(if $(MULTIFILE_ENABLED),$(call dblquote,$(MULTIFILEOBJECT) $(CIAFILES_LINKOBJECTS)),$(COMMANDFILE_OPTION)$(call dblquote,$(VIAFILE))) \
-          $(if $(GENERATELINKERFEEDBACK),$(FEEDBACK_OPTION)$(call dblquote,$(FEEDBACKFILE))) \
-	  $(if $(LINKER_ADD_STATIC_RUNTIME),$(if $(STATIC_RUNTIME_LIB),$(LINKER_GROUP_START_OPTION) $(STATIC_RUNTIME_DIR)/$(STATIC_RUNTIME_LIB) $(LINKER_GROUP_END_OPTION),)) \
-	  $(quoted_e32abiv2_LIBS) $(LINKER_DEFAULT_LIBS)\
-	$(call endrule,link)
-
-$(MAPFILE): $(LINK_TARGET)
-endef
-$(eval $(linktarget_func))
-
-CLEANTARGETS:=$(CLEANTARGETS) $(LINK_TARGET) $(if $(GENERATELINKERFEEDBACK),$(FEEDBACKFILE)) $(if $(MULTIFILE_ENABLED),$(MULTIFILEOBJECT))
-CLEANTARGETS:=$(CLEANTARGETS) $(VIAFILE)
-CLEANTARGETS:=$(CLEANTARGETS) $(MAPFILE)
-WHATRELEASE:=$(WHATRELEASE) $(MAPFILE)
-
-endif # if TARGETTYPE lib
-
-
-## Run trace compiler ##############################################
-ifeq ($(UID3),)
- ifeq ($(UID2),)
-  USE_TRACE_COMPILER:=
- else
-  UID_TC:=$(UID2)
- endif
-else
- UID_TC:=$(UID3)
-endif
-
-# USE_TRACE_COMPILER defaults to blank in Raptor config.
-# Users can turn TC on by setting it to 1 in user config.
-ifneq ($(USE_TRACE_COMPILER),)
-  include $(FLMHOME)/tracecompiler.mk
-endif
-
-CC_CPPONLY_ARGS:=$(SYMBIAN_CCFLAGS) $(if $(DEBUG_INFO),-g) $(DEBUG_FORMAT) \
-  $(RUNTIME_SYMBOL_VISIBILITY_OPTION) $(EXCEPTIONS) \
-  $(CC_WARNINGS_CONTROL_OPTION) $(CC_ERRORS_CONTROL_OPTION) \
-  $(TARGET_ARCH_OPTION) $(ENUM_OPTION) $(OWN_LIBRARY_OPTION) $(FPMODE_OPTION) \
-  $(EXPORT_VTBL_OPTION) $(NO_UNALIGNED_ACCESS) $(VFE_OPTION) $(AAPCS_OPTION) \
-  $(CPPONLYOPTION) $(INSTRUCTION_SET) \
-  $(if $(ALWAYS_BUILD_AS_ARM),$(ARM_INSTRUCTION_SET),$(THUMB_INSTRUCTION_SET) $(call makemacrodef,-D,$(COMPILER_THUMB_DEFINES))) \
-  $(COMPILER_FPU_FLAGS)
-
-## COMPILE CPP Files #################################################################
-
-# For ARMCC we can compile all sourcefiles with one invocation
-# The pathprep macro is used to make sure that forward slashes in options
-# are not interpreted as being paths by CYGWIN on Windows.  On windows
-# pathprep makes a forward slash into two.
-
-# The majority of ARMCC arguments are common across all compiler invocations
-# Order is significant here in that OPTION_REPLACE here and in ABLD should
-# have the same impact
-CC_CORE_ARGS:=$(SYMBIAN_CCFLAGS) $(if $(DEBUG_INFO),-g) $(DEBUG_FORMAT) \
-  $(RUNTIME_SYMBOL_VISIBILITY_OPTION) $(EXCEPTIONS) \
-  $(CC_WARNINGS_CONTROL_OPTION) $(CC_ERRORS_CONTROL_OPTION) \
-  $(TARGET_ARCH_OPTION) $(ENUM_OPTION) $(OWN_LIBRARY_OPTION) $(FPMODE_OPTION) \
-  $(EXPORT_VTBL_OPTION) $(NO_UNALIGNED_ACCESS) $(VFE_OPTION) $(AAPCS_OPTION) \
-  $(COMPILE_ONLY_OPTION) $(INSTRUCTION_SET) \
-  $(if $(ALWAYS_BUILD_AS_ARM),$(ARM_INSTRUCTION_SET),$(THUMB_INSTRUCTION_SET) $(call makemacrodef,-D,$(COMPILER_THUMB_DEFINES))) \
-  $(COMPILER_FPU_FLAGS)
-
-ifeq ($(STDCPP),1)
-SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$(call dblquote,$(STDCPP_INCLUDE)))
-endif
-
-define option_replace
-  # Process a single, combined, item of the form 'search<->replace' in order to modify the command line tool call
-  # We split this into its component arguments for use in substitutions
-  # Spaces will have been escaped elsewhere to maintain distinct words, so we resurrect these
-  # after the split.
-  SEARCH:=$(subst %20,$(CHAR_SPACE),$(word 1,$(subst <->,$(CHAR_SPACE),$(1))))
-  REPLACE:=$(subst %20,$(CHAR_SPACE),$(word 2,$(subst <->,$(CHAR_SPACE),$(1))))
-
-  # Depending on whether there's a wildcard in the search, we may require either a normal $(subst) or a $(patsubst)
-  PATSUBST:=$$(if $$(findstring %,$$(SEARCH)),1,)
-
-  ifeq ($$(PATSUBST),1)
-    CC_CORE_ARGS:=$$(patsubst $$(SEARCH),$$(REPLACE),$$(CC_CORE_ARGS))
-  else
-    CC_CORE_ARGS:=$$(subst $$(SEARCH),$$(REPLACE),$$(CC_CORE_ARGS))
-  endif
-endef
-$(foreach ITEM,$(OPTION_REPLACE_COMPILER),$(eval $(call option_replace,$(ITEM))))
-
-define e32abiv2_compile
-
-$(eval DEPENDFILENAME:=$(1).d)
-$(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
-
-# $4 is for language specific options (e.g. C++ vs C)
-$(1): $(2) $(PROJECT_META) $(if $(MULTIFILE_ENABLED),,$(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT)) $(if $(USE_TRACE_COMPILER),$(TRACE_MARKER),) $(if $(LINKERFEEDBACK_STAGE2),$(FEEDBACKFILE),)
-	$(call startrule,compile,,$(2))		\
-		$(if $(PERTURBSTARTTIME), $(RANSLEEP) $(PERTURBMSECS) ;,) \
-		$(if $(MULTIFILE_ENABLED), echo $(2) $(3) > $(MULTIFILE_VIAFILE) ;,) \
-		$(CC) $(LICENSERETRY_OPTION) \
-			$(CC_CORE_ARGS) \
-			$(OPTION_COMPILER) $(if $(MULTIFILE_ENABLED),$(4),$(3)) \
-			$(if $(LTCG),$(LTCG_OPTION),) \
-			$(if $(USE_PROFILER_FEEDBACK),--profile=$(call dblquote,$(ARM_PROFILER_FILE)),) \
-			$(call makemacrodef,-D,$(COMPILER_INTERWORK_DEFINES) $(CDEFS))				\
-			$(if $(PREINCLUDE),$(PREINCLUDE_OPTION) ,)$(call concat, $(PREINCLUDE_OPTION) ,$(call dblquote,$(PREINCLUDE)))\
-			$(if $(SET_ARMINC),$(if $(RVCTINC),$(COMPILER_SYSTEM_INCLUDE_OPTION)$(call dblquoteitem,$(RVCTINC)),),)       \
-			$(COMPILER_SYSTEM_INCLUDE_OPTION)$$(call dblquote,$$(<D))                                                      \
-			$(if $(USERINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$(call dblquote,$(USERINCLUDE)))      \
-			$(if $(SYSTEMINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$(call dblquote,$(SYSTEMINCLUDE)))  \
-			$(if $(NOHIDEALL),--no_hide_all,) \
-			$(DEPEND_OPTION) $(call dblquote,$(1).d) \
-                        $(if $(LINKERFEEDBACK_STAGE2),$(FEEDBACK_OPTION)$(call dblquote,$(FEEDBACKFILE))) \
-			$(if $(MULTIFILE_ENABLED),--multifile $(OUTPUT_OPTION) $(MULTIFILEOBJECT) \
-			--via $$(call dblquote, $(MULTIFILE_VIAFILE)),$(OUTPUT_OPTION) $$@ $$(call dblquote, $$<))  \
-	$(call endrule,compile)
-
-CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
-ifneq "$(DEPENDFILE)" ""
-ifeq ($(NO_DEPEND_INCLUDE),)
-  ifeq "$(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS)))" ""
-    -include $(DEPENDFILE)
-  endif
-endif
-endif
-
-# individual source file compilation
-SOURCETARGET_$(call sanitise,$(2)): $(1)
-
-endef
-
-# Evaluate .cpp and .c files in one go for multifile, cannot do in separate steps since we have the same target.
-# This implementation means the .c files will always get put at the end of the .via file. Maybe there is a better way to do this?
-$(if $(MULTIFILE_ENABLED),$(eval $(call e32abiv2_compile,$(MULTIFILEOBJECT),$(CPPFILES),$(CFILES),$(CPP_LANG_OPTION))),$(foreach F,$(CPPFILES),$(eval $(call e32abiv2_compile,$(call mapcpp2object,$(F)),$(F),$(CPP_LANG_OPTION)))))
-$(if $(MULTIFILE_ENABLED),,$(foreach F,$(CFILES),$(eval $(call e32abiv2_compile,$(call mapc2object,$(F)),$(F),$(C_LANG_OPTION)))))
-ifneq ($(TRANSFORM_CIA),1)
-  $(if $(MULTIFILE_ENABLED),,$(foreach F,$(CIAFILES),$(eval $(call e32abiv2_compile,$(call mapcia2object,$(F)),$(F),$(CPP_LANG_OPTION) $(COMPILER_CIA_FLAGS)))))
-endif
-
-CLEANTARGETS:=$(CLEANTARGETS) $(if $(MULTIFILE_ENABLED),$(MULTIFILE_VIAFILE) $(MULTIFILEOBJECT),$(CPPFILES_LINKOBJECTS) $(CFILES_LINKOBJECTS) $(CIAFILES_LINKOBJECTS)) $(if $(GENERATELINKERFEEDBACK),$(FEEDBACKFILE))
-
-## Listing target ###################################################
-# Very similar to compile, apart from the extra flags passed to the
-# compile and different output options
-
-define map2listfile
-$(call relocatefiles,$(INTERMEDIATEPATH),$(call extractandmap,$(CPPFILEEXTENSIONS) $(CFILEEXTENSIONS),.lis,$1))
-endef
-
-
-define e32abiv2_cpponly
-# $1 is the sourcefile
-
-$(eval CPPONLYTARGET:=$(strip $(call extractandmap,$(CPPFILEEXTENSIONS) $(CFILEEXTENSIONS),.$(subst _,.,$(call sanitise,$(FULLVARIANTPATH))).pre,$1)))
-
-CPPONLY:: $(CPPONLYTARGET)
-
-$(CPPONLYTARGET): $(1) $(PROJECT_META)  $(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT)
-	$(call startrule,e32cpponly,,$(1))		\
-		$(if $(PERTURBSTARTTIME), $(RANSLEEP) $(PERTURBMSECS) ;,) \
-		$(CC) $(LICENSERETRY_OPTION) $(SYMBIAN_CCFLAGS) \
-			$(CC_CPPONLY_ARGS) \
-			$(OPTION_COMPILER) 						\
-			$(call makemacrodef,-D,$(COMPILER_INTERWORK_DEFINES) $(CDEFS))				\
-			$(if $(PREINCLUDE),$(PREINCLUDE_OPTION) ,)$(call concat, $(PREINCLUDE_OPTION) ,$(call dblquote,$(PREINCLUDE)))\
-			$(if $(SET_ARMINC),$(if $(RVCTINC),$(COMPILER_SYSTEM_INCLUDE_OPTION)$(call dblquote,$(RVCTINC)),),)       \
-			$(COMPILER_SYSTEM_INCLUDE_OPTION)$$(call dblquote,$$(<D))                                                   \
-			$(if $(USERINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$(call dblquote,$(USERINCLUDE)))      \
-			$(if $(SYSTEMINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$(call dblquote,$(SYSTEMINCLUDE)))  \
-			$(if $(NOHIDEALL),--no_hide_all,) \
-			$$(call dblquote, $$<) $(OUTPUT_OPTION) $$(@) \
-	$(call endrule,e32cpponly)
-
-CLEANTARGETS:=$$(CLEANTARGETS) $(CPPONLYTARGET)
-endef
-
-ifneq ($(filter CPPONLY,$(call uppercase,$(MAKECMDGOALS))),)
-$(foreach F,$(CPPFILES) $(CFILES),$(eval $(call e32abiv2_cpponly,$(F))))
-endif
-
-define e32abiv2_listing
-# $1 is the sourcefile
-
-$(eval LISTINGTARGET:=$(strip $(call extractandmap,$(CPPFILEEXTENSIONS) $(CFILEEXTENSIONS),.$(subst _,.,$(call sanitise,$(FULLVARIANTPATH))).$(TARGET).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(POSTLINKFILETYPE)).lst,$1)))
-$(eval DEPENDFILENAME:=$(call map2listfile,$1).d)
-$(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
-
-
-LISTING:: $(LISTINGTARGET)
-
-$(LISTINGTARGET): $(1) $(PROJECT_META)  $(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT)
-	$(call startrule,e32listing,,$(1))		\
-		$(if $(PERTURBSTARTTIME), $(RANSLEEP) $(PERTURBMSECS) ;,) \
-		$(CC) $(LICENSERETRY_OPTION) $(SYMBIAN_CCFLAGS) \
-			$(CC_CORE_ARGS) \
-			$(LISTING_OPTION)		            	\
-			$(OPTION_COMPILER) 						\
-			$(call makemacrodef,-D,$(COMPILER_INTERWORK_DEFINES) $(CDEFS))				\
-			$(if $(PREINCLUDE),$(PREINCLUDE_OPTION) ,)$(call concat, $(PREINCLUDE_OPTION) ,$(call dblquote,$(PREINCLUDE)))\
-			$(if $(SET_ARMINC),$(if $(RVCTINC),$(COMPILER_SYSTEM_INCLUDE_OPTION)$(call dblquoteitem,$(RVCTINC)),),)       \
-			$(COMPILER_SYSTEM_INCLUDE_OPTION)$$(call dblquote,$$(<D))                                                   \
-			$(if $(USERINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$(call dblquote,$(USERINCLUDE)))      \
-			$(if $(SYSTEMINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$(call dblquote,$(SYSTEMINCLUDE)))  \
-			$(if $(NOHIDEALL),--no_hide_all,) \
-			$(DEPEND_OPTION) $(call dblquote,$(DEPENDFILENAME)) \
-			$$(call dblquote, $$<) $(OUTPUT_OPTION) $$(@) \
-	$(call endrule,e32listing)
-
-CLEANTARGETS:=$$(CLEANTARGETS) $(LISTINGTARGET)
-
-CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
-ifneq "$(DEPENDFILE)" ""
-ifeq ($(NO_DEPEND_INCLUDE),)
-  ifeq "$(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS)))" ""
-    -include $(DEPENDFILE)
-  endif
-endif
-endif
-
-endef
-
-# No point at all in generating listing targetsif we aren't going to make them
-ifneq ($(filter LISTING,$(call uppercase,$(MAKECMDGOALS))),)
-$(foreach F,$(CPPFILES) $(CFILES),$(eval $(call e32abiv2_listing,$(F))))
-endif
-
-
-
-# Function to execute FREEZE ###########################################
-ifneq ($(SUPPORT_FREEZE),)
-
-# Fivespaces variable created to ensure a suitable gap of space characters
-# Is placed between the separate arguments. This fixes a problem in Cygwin, where
-# separate arguments are interpreted as a single argument when passed to bash
-FIVESPACES=$(BLANK)     $(BLANK)
-
-FREEZEGUARD:=TARGET_$(TARGET)_$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(POSTLINKFILETYPE))_$(IMPORTLIBPATH)_EFREEZE
-
-define e32freeze
-
-FREEZE:: $(1)
-	$(call startrule,freeze,,$(RESOLVED_DEFFILE)) \
-	$(EFREEZE) $(EFREEZE_REMOVE_OPTION) "$(RESOLVED_DEFFILE)" $(FIVESPACES) $(GENERATED_DEFFILE) \
-	$(call endrule,freeze)
-endef
-
-# DEFFILE should only be generated for target types that have a def file
-ifeq ($(MAKEDEFFILE),1)
-# Eval freeze only once - no point making the DEFFILE for urel *and* udeb.
-ifeq ($($(FREEZEGUARD)),)
-$(eval $(call e32freeze,$(E32TARGET)))
-$(FREEZEGUARD):=1
-endif
-endif
-
-endif
-
-CLEANTARGETS:=$(CLEANTARGETS) $(if $(MULTIFILE_ENABLED),$(MULTIFILEOBJECT),$(CPPFILES_LINKOBJECTS) $(CFILES_LINKOBJECTS))
-
-## ASSEMBLER FILES ###################################################################
-# CIA VERSION      ############################################
-define mapcia2xxx
-$(call relocatefiles,$(INTERMEDIATEPATH),$(call extractandmap,$(CIAFILEEXTENSIONS),$2,$1))
-endef
-
-define e32abiv2_CIA2CPP
-
-$(eval e32abiv2_OFILE:=$(call mapcia2xxx,$(1),_.o))
-$(eval e32abiv2_PREFILE:=$(call mapcia2xxx,$(1),_.pre))
-$(eval e32abiv2_CPPFILE:=$(call mapcia2xxx,$(1),_.cpp))
-$(eval CLEANTARGETS:=$(CLEANTARGETS) $(e32abiv2_OFILE) $(e32abiv2_CPPFILE) $(e32abiv2_PREFILE))
-
-$(e32abiv2_OFILE): $(e32abiv2_CPPFILE) $(PROJECT_META)
-	$(call startrule,cia2cpp2o,,$(e32abiv2_CPPFILE)) \
-		$(if $(PERTURBSTARTTIME),$(RANSLEEP) $(PERTURBMSECS) ;,) \
-			$(CC) $(LICENSERETRY_OPTION) \
-			$(CC_CORE_ARGS) \
-			$(if $(LTCG),$(LTCG_OPTION),) \
-			$(OPTION_COMPILER) \
-			$(call makemacrodef,-D,$(COMPILER_INTERWORK_DEFINES) $(CDEFS) $(CIADEFS)) $(CPP_LANG_OPTION)      \
-	 		$(if $(USERINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$$(call dblquote,$(USERINCLUDE)))     \
-	 		$(if $(SYSTEMINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$$(call dblquote,$(SYSTEMINCLUDE))) \
-	 		$$(call dblquote, $$<) $(OUTPUT_OPTION) $$@ \
-	$(call endrule,cia2cpp2o)
-
-
-# preprocessed CIA file to a CPP file
-$(e32abiv2_CPPFILE): $(e32abiv2_PREFILE)
-	$(call startrule,tranasm) \
-	$(if $(CPPFILT),CPPFILT="$(CPPFILT)",) \
-	$(TRANASM) --suppress-check --output="$$@" $$^ \
-	$(call endrule,tranasm)
-
-$(eval DEPENDFILENAME:=$(e32abiv2_PREFILE).d)
-$(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
-
-# preprocess the cia file
-$(eval e32abiv2_PREFILE_OPTIONS:= $(LICENSERETRY_OPTION) $(PREPROCESSOR_OPTION) $(CPP_OPTION) \
-       $(SYMBIAN_CCFLAGS) $(call makemacrodef,-D,$(COMPILER_INTERWORK_DEFINES) $(CDEFS) $(CIADEFS)) $(CPP_LANG_OPTION) \
-       $(if $(PREINCLUDE),$(PREINCLUDE_OPTION) ,)$$(call concat, $(PREINCLUDE_OPTION) ,$$(call dblquote,$(PREINCLUDE))) \
-       $(if $(USERINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$$(call dblquote,$(USERINCLUDE))) \
-       $(if $(SYSTEMINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$$(call dblquote,$(SYSTEMINCLUDE))) \
-       $(if $(ARMINC),$(if $(RVCTINC), $(COMPILER_SYSTEM_INCLUDE_OPTION)$$(call dblquoteitem,$(RVCTINC)),),) )
-
-
-$(e32abiv2_PREFILE): $1 $(PROJECT_META) $(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT)
-	$(call startrule,cia2cpp,,$1) \
-	$(if $(PERTURBSTARTTIME),$(RANSLEEP) $(PERTURBMSECS) ;,) \
-	$(CC) $(e32abiv2_PREFILE_OPTIONS) $(OUTPUT_OPTION) $$@ $$(call dblquote,$1) && \
-	$(CC) -M $(e32abiv2_PREFILE_OPTIONS) --depend_format=unix \
-	  $(OUTPUT_OPTION) $$@ $$(call dblquote,$1) > $(call dblquote,$(e32abiv2_PREFILE).d) \
-	$(call endrule,cia2cpp)
-
-CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
-ifneq "$(DEPENDFILE)" ""
-ifeq ($(NO_DEPEND_INCLUDE),)
-  ifeq "$(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS)))" ""
-    -include $(DEPENDFILE)
-  endif
-endif
-endif
-
-endef
-
-# Create a rule for each cia file
-ifeq ($(TRANSFORM_CIA),1)
-  $(eval $(foreach e32abiv2_RULE,$(CIAFILES),$(call e32abiv2_CIA2CPP,$(e32abiv2_RULE))))
-endif
-
-# Pure assembler (.s files) ################################
-
-e32abiv2_asm_OPTIONS:=$(LICENSERETRY_OPTION) \
-  $(CC_CORE_ARGS) \
-  $(OPTION_COMPILER) \
-  $(call makemacrodef,-D,$(COMPILER_INTERWORK_DEFINES) $(CDEFS)) \
-  $(if $(USERINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$$(call dblquote,$(USERINCLUDE)))     \
-  $(if $(SYSTEMINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$$(call dblquote,$(SYSTEMINCLUDE)))
-
-# note that the --no_rtti option cannot be passed with the -M option
-# so forcibly remove it when generating ASM dependencies.
-#
-define e32abiv2_asm
-
-$(eval DEPENDFILENAME:=$(1).d)
-$(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
-
-$(1): $(2) $(PROJECT_META) $(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT)
-	$(call startrule,asmcompile,,$(2)) \
-		$(if $(PERTURBSTARTTIME),$(RANSLEEP) $(PERTURBMSECS) ;,) \
-		$(CC) $(e32abiv2_asm_OPTIONS) \
-		$(DEPEND_OPTION) $(call dblquote,$(DEPENDFILENAME)) \
-	 	$$(call dblquote, $$<) $(OUTPUT_OPTION) $$@ \
-	$(call endrule,asmcompile)
-	$(call startrule,asmdependencies) \
-		$(CC) -M $(subst --no_rtti,,$(e32abiv2_asm_OPTIONS)) --depend_format=unix \
-	  	$(OUTPUT_OPTION) $$@ $$(call dblquote,$2) > $(call dblquote,$(DEPENDFILENAME)) \
-	$(call endrule,asmdependencies)
-
-CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
-ifneq "$(DEPENDFILE)" ""
-ifeq ($(NO_DEPEND_INCLUDE),)
-  ifeq "$(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS)))" ""
-    -include $(DEPENDFILE)
-  endif
-endif
-endif
-
-CREATABLEPATHS:=$$(CREATABLEPATHS) $(INTERMEDIATEPATH)
-
-endef
-
-$(eval $(foreach F,$(ASMFILES), $(call e32abiv2_asm,$(call mapasm2object,$(F)),$(F))))
-CLEANTARGETS:=$(CLEANTARGETS) $(ASMFILES_LINKOBJECTS)
-
-endif # ifneq ($(TARGETTYPE),implib)
-
-
-########################## Build ROMFILE target ############################
-EPOC_ROOT:=$(patsubst %/,%,$(EPOCROOT))
-TOBLDINF:=$(dir $(subst :,,$(subst $(EPOC_ROOT)/,,$(COMPONENT_META))))
-
-# Only build ROMFILE if asked
-ifneq ($(filter ROMFILE,$(call uppercase,$(MAKECMDGOALS))),)
-    ifeq ($(ROMFILE_$(call sanitise,$(TARGET).$(REQUESTEDTARGETEXT))),)
-        ROMFILE_$(call sanitise,$(TARGET).$(REQUESTEDTARGETEXT)):=1
-        ROMDIR:=$(EPOC_ROOT)/epoc32/rom/$(TOBLDINF)
-
-        # Default values
-        ROMFILETYPE:=file
-        ROMFILE:=$(TARGET).$(REQUESTEDTARGETEXT)
-        ROMPATH:=sys/bin/
-        ROMDECORATIONS:=
-        ROMFILETYPE_RAM:=data
-        ROMFILE_RAM:=$(TARGET).$(REQUESTEDTARGETEXT)
-        ROMPATH_RAM:=sys/bin/
-        BUILDROMTARGET:=1
-        ABIDIR:=MAIN
-
-        $(eval $(call DoRomSet))
-
-        ifneq ($(EPOCFIXEDPROCESS),)
-            ROMDECORATIONS:=$(ROMDECORATIONS) fixed
-        endif
-        ifeq ($(PAGED),1)
-            ROMDECORATIONS:=$(ROMDECORATIONS) paged
-        endif
-        ifeq ($(PAGED),0)
-            ROMDECORATIONS:=$(ROMDECORATIONS) unpaged
-        endif
-
-
-        ifeq ($(TESTCODE),TRUE)
-        	# Add 'TEST' to the .iby filename
-        	ROMTEST:=test
-            ifeq ($(TEST_OPTION),BOTH)
-                DATATEXT:="data=/epoc32/data/z/test/$(MODULE)/$(VARIANTPLATFORM).auto.bat test/$(MODULE).auto.bat"\n"data=/epoc32/data/z/test/$(MODULE)/$(VARIANTPLATFORM).manual.bat test/$(MODULE).manual.bat"
-            else
-                ifneq ($(TEST_OPTION),NONE)
-                    DATATEXT:="data=/epoc32/data/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TEST_OPTION).bat test/$(MODULE).$(TEST_OPTION).bat"
-                endif
-            endif
-        else
-        	DATATEXT:=
-        endif
-
-        # ROMTARGET
-        ifneq ($(ROMTARGET),)
-            ifneq ($(words $(ROMTARGET)),1)
-                ROMTARGETALL:=$(ROMTARGET)
-                ROMTARGET:=$(word 1,$(ROMTARGET))
-            endif
-
-            ifeq ($(ROMTARGET),<none>)
-                BUILDROMTARGET:=
-            else
-                ifneq ($(ROMTARGET),+)
-                    ifneq ($(notdir $(ROMTARGET)),)
-                        ROMFILE:=$(notdir $(ROMTARGET))
-                    endif
-                    ifneq ($(dir $(ROMTARGET)),./)
-                        ROMPATH:=$(dir $(ROMTARGET))
-                    endif
-                endif
-            endif
-        endif
-    endif
-
-    ROMFILENAME:=$(ROMDIR)$(PLATFORM)$(ROMTEST).iby
-
-    # RAMTARGET
-    ifneq ($(RAMTARGET),)
-        ROMDECORATIONS_RAM:=" attrib=r"
-        ifneq ($(RAMTARGET),+)
-            ifneq ($(notdir $(RAMTARGET)),)
-                ROMFILE_RAM:=$(notdir $(RAMTARGET))
-            endif
-            ifneq ($(dir $(RAMTARGET)),./)
-                ROMPATH_RAM:=$(dir $(RAMTARGET))
-            endif
-        endif
-    endif
-
-    define BuildRomfileTarget
-        $(ALLTARGET)::ROMFILE
-        ROMFILE::
-	        $(call startrule,rombuild)	\
-	        $(GNUMKDIR) -p $(ROMDIR) \
-            $(if $(ROMFILE_CREATED_$(TOBLDINF)),,&& echo -e "// $(subst $(EPOC_ROOT)/,,$(ROMFILENAME))\n//\n$(DATATEXT)" > $(ROMFILENAME)) \
-            $(if $(BUILDROMTARGET),&& echo "$(ROMFILETYPE)=/epoc32/release/##$(ABIDIR)##/##BUILD##/$(TARGET).$(REQUESTEDTARGETEXT)   $(1)$(ROMDECORATIONS)" >> $(ROMFILENAME))	\
-	        $(if $(RAMTARGET),&& echo "$(ROMFILETYPE_RAM)=/epoc32/release/##$(ABIDIR)##/##BUILD##/$(TARGET).$(REQUESTEDTARGETEXT)   $(ROMPATH_RAM)$(ROMFILE_RAM)$(ROMDECORATIONS_RAM)" >> $(ROMFILENAME))	\
-	        $(call endrule,buildromfiletarget)
-    endef
-
-    # When VARIANTTYPE changes, romfile is finished,
-    # apart from if this is a new component......
-    ifneq ($(PREVIOUSVARIANTTYPE),)
-        ifneq ($(VARIANTTYPE),$(PREVIOUSVARIANTTYPE))
-            ifneq ($(ROMFILE_CREATED_$(TOBLDINF)),)
-                ROMFILEFINISHED:=1
-            else
-                ROMFILEFINISHED:=
-            endif
-        endif
-    endif
-
-    # When romfile is finished, don't continue to add to it
-    ifeq ($(ROMFILEFINISHED),)
-        $(eval $(call BuildRomfileTarget,$(ROMPATH)$(ROMFILE)))
-    endif
-
-    # Don't allow romfile to be recreated for every MMP
-    ifeq ($(ROMFILE_CREATED_$(TOBLDINF)),)
-        ROMFILE_CREATED_$(TOBLDINF):=1
-    endif
-
-    # Build other ROMTARGETs if there is more than one
-    ifneq ($(ROMTARGETALL),)
-        RAMTARGET:=
-        $(foreach ROMTARGET,$(wordlist 2,$(words $(ROMTARGETALL)),$(ROMTARGETALL)),$(eval $(call BuildRomfileTarget,$(ROMTARGET))))
-        ROMTARGETALL:=
-    endif
-
-    # Keep track of variant type while romfile is being created
-    PREVIOUSVARIANTTYPE:=$(VARIANTTYPE)
-
-    WHATRELEASE:=$(WHATRELEASE) $(ROMFILENAME)
-    CLEANTARGETS:=$(CLEANTARGETS) $(ROMFILENAME)
-endif
-
-# Deal with test code batch files generation.
-ifneq ($(TESTPATH),)
-
-    CREATABLEPATHS:=$(CREATABLEPATHS) $(EPOCROOT)/epoc32/data/z/test/
-    $(eval $(call MakeTestBatchFiles,$(TARGET),$(EPOCROOT)/epoc32/data/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH)))
-    BATCHFILE_CREATED_$(EPOCROOT)/epoc32/data/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH):=1
-    TARGET_CREATED_$(EPOCROOT)/epoc32/data/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH)_$(TARGET):=1
-    WHATRELEASE:=$(WHATRELEASE) $(EPOCROOT)/epoc32/data/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH)
-    CLEANTARGETS:=$(CLEANTARGETS) $(EPOCROOT)/epoc32/data/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH)
-endif
-
-###################### End of Build ROMFILE target ######################
-
-# Feature Variation requires a .vmap file to be created for each binary
-#
-ifneq ($(FEATUREVARIANTNAME),)
-ifneq ($(E32TARGET),)
-
-OUTPUTVMAP:=$(E32TARGET).vmap
-WHATRELEASE:=$(WHATRELEASE) $(OUPUTVMAP)
-
-TARGET:: $(OUTPUTVMAP)
-VMAPNEEDS:=$(E32TARGET) $(SOURCE) $(PROJECT_META)
-
-BV_SOURCELIST:=$(addprefix -s ,$(SOURCE) $(PROJECT_META))
-BV_FEATURELIST:=$(addprefix -f ,$(FEATURELISTFILES))
-BV_USER_INCLUDES:=$(addprefix -u ,$(USERINCLUDE))
-BV_SYSTEM_INCLUDES:=$(addprefix -x ,$(SYSTEMINCLUDE))
-
-# translate double quoted macros because $(shell) messes them up in some make engines
-BV_MACROLIST:=$(COMPILER_INTERWORK_DEFINES) $(CDEFS) $(if $(ALWAYS_BUILD_AS_ARM),,$(COMPILER_THUMB_DEFINES))
-BV_DEFINES:=$(call makemacrodef,-D,$(subst ",__SBS__QUOTE__,$(BV_MACROLIST)))
-
-# the script to generate our .vmap file and hash value
-VMAPCOMMAND:=$(CREATEVMAP) -o $(OUTPUTVMAP) $(BV_FEATURELIST) $(BV_DEFINES) -p $(PREINCLUDE) $(BV_SOURCELIST) $(BV_USER_INCLUDES) $(BV_SYSTEM_INCLUDES) -c $(CREATEVMAPCPP)
-
-# a recipe to create the .vmap from the "sources" with the createvmap script
-$(call raptor_recipe,createvmap,$(OUTPUTVMAP),$(VMAPNEEDS),$(VMAPCOMMAND))
-
-endif # E32TARGET != ""
-endif # FEATUREVARIANTNAME != ""
-
-########################### CONCLUSION ###################################
-
-# make the output directories while reading makefile - some build engines prefer this
-$(call makepath,$(CREATABLEPATHS))
-
-## Clean up
-$(eval $(call GenerateStandardCleanTarget,$(CLEANTARGETS) ,$(CREATABLEPATHS),))
-
-# For the abld -what target
-$(eval $(call whatmacro,$(filter-out %.sym,$(WHATRELEASE)),WHATARMV5))
-
-endif # FEATUREVARIANTNAME=="" or FEATUREVARIANT==1
-
-## The End
-
+# 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:
+# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
+# Knows how to build all possible ABIV2 executables for ARM
+#
+#
+
+# Feature/Binary Variation
+#
+# FEATUREVARIANTNAME != "" implies a product build configuration
+# FEATUREVARIANT == 1 implies a .mmp defined feature variant binary
+#
+# By default:
+#   Build all binaries in non-product builds *and*
+#   Only build feature variant binaries in product builds.
+#
+#   test FEATUREVARIANTNAME=="" or FEATUREVARIANT==1
+#
+# If FEATUREVARIANTSAFE is set:
+#   Only build feature invariant binaries in non-product builds *and*
+#   Only build feature variant binaries in product builds.
+#
+#   test (FEATUREVARIANTNAME=="" and FEATUREVARIANT=="") or
+#        (FEATUREVARIANTNAME!="" and FEATUREVARIANT==1)
+#
+
+DOBUILD:=
+ifeq ($(FEATUREVARIANTSAFE),)
+  DOBUILD:=$(if $(or $(call equal,$(FEATUREVARIANTNAME),),\
+                     $(call equal,$(FEATUREVARIANT),1)),1)
+else
+  DOBUILD:=$(if $(or $(and $(call equal,$(FEATUREVARIANTNAME),),\
+                           $(call equal,$(FEATUREVARIANT),)),\
+                     $(and $(call not,$(call equal,$(FEATUREVARIANTNAME),)),\
+                           $(call equal,$(FEATUREVARIANT),1))),1)
+endif
+
+ifeq ($(DOBUILD),1)
+
+$(if $(FLMDEBUG),$(info <debug><flm name='e32abiv2' target='$(TARGET)' type='$(TARGETTYPE)' outputpath='$(OUTPUTPATH)' metasource='$(METASOURCE)' postlinkfiletype='$(POSTLINKFILETYPE)' /></debug>))
+
+# Enable DELETE_ON_FAILED_COMPILE work around for failed RVCT 2.2 compiles
+ifneq ($(DELETE_ON_FAILED_COMPILE),)
+RVCT22_DELETE_WORKAROUND:=|| { $$(GNURM) $$@; exit 1; }
+endif # ifneq ($(DELETE_ON_FAILED_COMPILE),)
+
+# Strip switch-type parameters
+#
+POSTLINKTARGETTYPE:=$(strip $(POSTLINKTARGETTYPE))
+TARGETEXT:=$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(POSTLINKFILETYPE))
+
+UID1:=$(strip $(UID1))
+UID2:=$(strip $(UID2))
+UID3:=$(strip $(UID3))
+SID:=$(strip $(SECUREID))
+VENDORID:=$(strip $(VENDORID))
+AUTOEXPORTS:=$(strip $(AUTOEXPORTS))
+DEFFILE:=$(strip $(DEFFILE))
+IMPORTLIBRARYREQUIRED:=$(strip $(IMPORTLIBRARYREQUIRED))
+EPOCALLOWDLLDATA:=$(strip $(EPOCALLOWDLLDATA))
+PAGED:=$(strip $(PAGED))
+
+# the output directories
+VARIANTPLATFORM:=$(VARIANTPLATFORM)$(FEATUREVARIANTNAME)
+RELEASABLEPATH:=$(RELEASEPATH)/$(VARIANTPLATFORM)/$(VARIANTTYPE)
+INTERMEDIATEPATH:=$(OUTPUTPATH)/$(VARIANTPLATFORM)/$(VARIANTTYPE)
+INTERMEDIATE_PLATFORM_PATH:=$(OUTPUTPATH)/$(VARIANTPLATFORM)
+TRACE_MARKER_PATH:=$(OUTPUTPATH)
+IMPORTLIBPATH:=$(RUNTIME_LIBS_PATH)
+
+# LOCALLY USED VARIABLES
+CLEANTARGETS:=
+WHATRELEASE:=
+
+# Work out which new/delete library to use for binaries.
+CHECKLIB_TYPE:=symc++
+STDCPPTAGFILE:=
+ifeq ($(NOSTDCPP),1)
+  ifeq ($(STDCPP),1)
+    $(info <warning>STDCPP and NOSTDCPP both specified in $(PROJECT_META)</warning>)
+  else
+    ifeq ($(HAS_DEDICATED_OP_NEWDEL_LIB),1)
+      DEFAULT_NEWLIB:=$(DEFAULT_SYMBIAN_NEWLIB)
+    endif
+  endif
+else
+  ifeq ($(STDCPP),1)
+    CDEFS:=$(CDEFS) __SYMBIAN_STDCPP_SUPPORT__
+    ifneq ($(SUPPORTS_STDCPP_NEWLIB),)
+      ifeq ($(HAS_DEDICATED_OP_NEWDEL_LIB),1)
+        DEFAULT_NEWLIB:=$(DEFAULT_STDCPP_NEWLIB)
+      endif
+      CHECKLIB_TYPE:=stdc++
+      STDCPPTAGFILE:=$(EPOCROOT)/epoc32/tools/tag/tag_elf
+    endif
+  endif
+endif
+
+# If NEWLIB is specified in the MMP file, it overrides all the past stuff.
+ifeq ($(NEWLIB),)
+  NEWLIB:=$(DEFAULT_NEWLIB)
+endif
+
+
+##########################################################################
+## OUTPUTS - externally relevant targets that this FLM generates
+
+
+ifeq ($(EXPORTLIBRARY),)
+  EXPORTLIBRARY:=$(TARGET)
+endif
+
+# This will insert the file version between the name and the extension.
+# If there is more than one dot in generated filename the inserted position will be
+# BEFORE the last but two dot. E.g name1.name2.name3.dll to name1.name2{version}.name3.dll
+LIBEXT:=$(lastword $(subst .,$(CHAR_SPACE) ,$(EXPORTLIBRARY)))
+LIBBASE:=$(patsubst %.$(LIBEXT),%,$(EXPORTLIBRARY))
+ifneq ($(findstring .,$(EXPORTLIBRARY)),)
+  # Please note $(EXPORTLIBRARY) doesn't include target type.
+  VER_E32IMPORTLIBBASE:=$(IMPORTLIBPATH)/$(LIBBASE){$(VERSIONHEX)}.$(LIBEXT)
+else
+  VER_E32IMPORTLIBBASE:=$(IMPORTLIBPATH)/$(EXPORTLIBRARY){$(VERSIONHEX)}
+endif
+
+# Postlinkable targets need to be linked and elf2e32'd
+ifneq ($(DOPOSTLINK),)
+    E32TARGET:=$(RELEASABLEPATH)/$(TARGET)$(if $(EXPLICITVERSION),{$(VERSIONHEX)},).$(TARGETEXT)
+    LINK_TARGET:=$(RELEASABLEPATH)/$(TARGET)$(if $(EXPLICITVERSION),{$(VERSIONHEX)},).$(TARGETEXT).sym
+    MAPFILE:=$(RELEASABLEPATH)/$(TARGET).$(TARGETEXT).map
+else
+  E32TARGET:=
+  LINK_TARGET:=
+  MAPFILE:=
+endif
+
+# libs and klibs, on the other hand need to be archived
+ifneq ($(call isoneof,$(TARGETTYPE),lib klib stdlib),)
+  ARTARGET:=$(RELEASABLEPATH)/$(TARGET).lib
+  # We need libs and klibs before we can link stuff with them:
+  LIBRARY:: $(ARTARGET)
+else
+  ARTARGET:=
+endif
+
+
+ifneq ($(IMPORTLIBRARYREQUIRED),) # no dso files for plugins, animation dlls etc
+  # make sure we don't build import libraries more than once for UDEB and UREL
+  # Without this, wierd target-specific variable problems happen with LIBRARY in particular
+
+  TMP_IMPORTLIBTARGET_ROOT:=$(IMPORTLIBPATH)/$(EXPORTLIBRARY)
+
+  # ABIv2 .dso
+  IMPORTLIBTARGET_DSO:=
+  IMPORTLIBTARGETVERSIONED_DSO:=
+
+  BUILDMARKER_IMPORTLIBTARGET_DSO:=TARGET_$(subst :,,$(VER_E32IMPORTLIBBASE)).dso
+  WHATRELEASE:=$(WHATRELEASE) $(if $(EXPLICITVERSION),,$(TMP_IMPORTLIBTARGET_ROOT).dso)
+  WHATRELEASE:=$(WHATRELEASE) $(VER_E32IMPORTLIBBASE).dso
+  ifeq ($($(BUILDMARKER_IMPORTLIBTARGET_DSO)),)
+    IMPORTLIBTARGET_DSO:=$(TMP_IMPORTLIBTARGET_ROOT).dso
+    IMPORTLIBTARGETVERSIONED_DSO:=$(VER_E32IMPORTLIBBASE).dso
+  endif
+
+  # ABIv1 .lib (for specific kits and toolchains only)
+  IMPORTLIBTARGET_LIB:=
+  IMPORTLIBTARGETVERSIONED_LIB:=
+  BUILDMARKER_IMPORTLIBTARGET_LIB:=TARGET_$(subst :,,$(VER_E32IMPORTLIBBASE)).lib
+  # Only for kits that require and tools that support them
+  ifneq ($(SUPPORTS_ABIV1_IMPLIBS),)
+    WHATRELEASE:=$(WHATRELEASE) $(if $(EXPLICITVERSION),,$(TMP_IMPORTLIBTARGET_ROOT).lib)
+    WHATRELEASE:=$(WHATRELEASE) $(VER_E32IMPORTLIBBASE).lib
+    ifeq ($($(BUILDMARKER_IMPORTLIBTARGET_LIB)),)
+      IMPORTLIBTARGET_LIB:=$(TMP_IMPORTLIBTARGET_ROOT).lib
+      IMPORTLIBTARGETVERSIONED_LIB:=$(VER_E32IMPORTLIBBASE).lib
+    endif
+  endif
+endif
+
+# Try to make sure that we get the right linkas name
+# If linkas is specified then split it up and
+# put the hex version number in the right place
+ifeq ($(LINKAS),)
+  LINKASNAME=$(TARGET)
+  LINKASTYPE=$(TARGETEXT)
+else
+  SPLIT_LINKAS=$(subst ., ,$(LINKAS))
+  LINKASNAME=$(word 1,$(SPLIT_LINKAS))
+  LINKASTYPE=$(word 2,$(SPLIT_LINKAS))
+endif
+
+# ignore UID3 if it is zero
+ifeq ($(UID3),00000000)
+  LINKASVERSIONED=$(LINKASNAME){$(VERSIONHEX)}.$(LINKASTYPE)
+else
+  LINKASVERSIONED=$(LINKASNAME){$(VERSIONHEX)}$(if $(UID3),[$(UID3)],).$(LINKASTYPE)
+endif
+
+##########################################################################
+## TARGET GROUPS ##
+RELEASABLES:=$(strip $(E32TARGET) $(ARTARGET) $(LINK_TARGET) $(MAPFILE))
+# More targets to be added later
+TARGETS:=$(strip $(E32TARGET) $(IMPORTLIBTARGET) $(LINK_TARGET) $(ARTARGET))
+
+CREATABLEPATHS:=$(OUTPUTPATH)
+CREATABLEPATHS:=$(CREATABLEPATHS) $(INTERMEDIATE_PLATFORM_PATH)
+CREATABLEPATHS:=$(CREATABLEPATHS) $(INTERMEDIATEPATH)
+CREATABLEPATHS:=$(CREATABLEPATHS) $(RELEASABLEPATH)
+CREATABLEPATHS:=$(CREATABLEPATHS) $(RUNTIME_LIBS_PATH)
+CREATABLEPATHS:=$(CREATABLEPATHS) $(IMPORTLIBPATH)
+WHATRELEASE:=$(WHATRELEASE) $(RELEASABLES)
+
+
+
+## HIGH LEVEL Targets ##
+.PHONY:: $(ALLTARGET)
+
+## GLOBAL TARGETS ############################################################
+$(ALLTARGET):: $(RELEASABLES)
+TARGET:: $(RELEASABLES)
+
+## Internal targets ##
+
+# Determine the name of the generated DSO file ###############################
+# This is to generate the dso with the Some{Versionhex}.file.dso
+# It reproduces what appears to be a problem in the current build system
+# that affects messageintercept{000a0000}.esockdebug.dso whose
+# filename differs from it's "linkas" name.
+E32VAR:=$(subst .,$(CHAR_SPACE) ,$(TARGET))
+E32SOME:=$(word 1,$(E32VAR))
+E32VAR2:=$(patsubst $(E32SOME).%,%,$(TARGET))
+
+# Separate '_SH' variables created for output into bash - Preserves '{' and '}'
+
+ifneq ($(findstring .,$(TARGET)),)
+	DSODEFFILENAMEBASE:=$(E32SOME){$(VERSIONHEX)}.$(E32VAR2)
+else
+	DSODEFFILENAMEBASE:=$(TARGET){$(VERSIONHEX)}
+endif
+GENERATED_DSO:=$(call dblquote,$(INTERMEDIATEPATH)/$(DSODEFFILENAMEBASE).dso)
+GENERATED_DEFFILE:=$(INTERMEDIATEPATH)/$(DSODEFFILENAMEBASE).def
+
+## IMPORT LIBRARY  ###########################################################
+
+# Static libraries will be postlinked when they are used so don't try to postlink them
+
+ifneq ($(IMPORTLIBRARYREQUIRED),)
+ifneq ($(or $(DEFFILE),$(EXPORTUNFROZEN)),)
+# Both ABIv2 .dso and ABIv1 .lib import library generation require a processed .def file,
+# unless EXPORTUNFROZEN is being used
+PREPPEDDEFFILE:=
+ifneq ($(DEFFILE),)
+  ifeq ($(EXPORTUNFROZEN),)
+    PREPPEDDEFFILE:=$(INTERMEDIATEPATH)/$(TARGET).prep
+    CLEANTARGETS:=$(CLEANTARGETS) $(PREPPEDDEFFILE)
+    define importlibtarget_prepfile
+      $(PREPPEDDEFFILE): $(DEFFILE)
+		$(call startrule,importlibtarget_prepfile,FORCESUCCESS) \
+		$(PREPDEF) $(call dblquote,$(DEFFILE)) $(call dblquote,$(PREPPEDDEFFILE)) \
+		$(call endrule,importlibtarget_prepfile)
+    endef
+    $(eval $(importlibtarget_prepfile))
+  endif
+endif
+
+# ABIv2 .dso
+ifneq ($(IMPORTLIBTARGET_DSO),) # check that we haven't tried to specify this target already
+
+  # By Now we're committed to producing a target for this DSO so it's safe to
+  # set the marker that will prevent any further targets from being made.
+  $(eval $(BUILDMARKER_IMPORTLIBTARGET_DSO):=1)
+
+  ifneq ($(EXPLICITVERSION),)
+    TARGETS:=$(strip $(TARGETS) $(IMPORTLIBTARGETVERSIONED_DSO))
+
+    # Add this importlibrary to our global targets
+    LIBRARY:: $(IMPORTLIBTARGETVERSIONED_DSO)
+    $(ALLTARGET):: $(IMPORTLIBTARGETVERSIONED_DSO)
+    TARGET:: $(IMPORTLIBTARGETVERSIONED_DSO)
+
+  else
+    TARGETS:=$(strip $(TARGETS) $(IMPORTLIBTARGETVERSIONED_DSO) $(IMPORTLIBTARGET_DSO))
+
+    # Add this importlibrary to our global targets
+    LIBRARY:: $(IMPORTLIBTARGET_DSO)
+    $(ALLTARGET):: $(IMPORTLIBTARGETVERSIONED_DSO) $(IMPORTLIBTARGET_DSO)
+    TARGET:: $(IMPORTLIBTARGETVERSIONED_DSO) $(IMPORTLIBTARGET_DSO)
+
+
+  endif
+
+
+
+  ifneq ($(EXPORTUNFROZEN),) # Unfrozen  - warn and create .dso as side-effect of the final postlink
+    $(info <warning project='$(PROJECT_META)' component='$(COMPONENT_META)'>EXPORTUNFROZEN present in $(PROJECT_META) - unfrozen exports will be represented in import library.</warning> )
+    define importlibtarget_unfrozen
+      $(IMPORTLIBTARGET_DSO): $(IMPORTLIBTARGETVERSIONED_DSO)
+		$(call startrule,importlibtarget_unfrozen,FORCESUCCESS) \
+		$(GNUCP) $$(call dblquote,$$<) $$(call dblquote,$$@) \
+		$(call endrule,importlibtarget_unfrozen)
+    endef
+
+    define importlibtarget_unfrozen_ver
+      $(IMPORTLIBTARGETVERSIONED_DSO): $(E32TARGET)
+		$(call startrule,importlibversioned_unfrozen,FORCESUCCESS) \
+		$(GNUCP) "$(GENERATED_DSO)" "$$@" \
+		$(call endrule,importlibversioned_unfrozen)
+    endef
+
+    ifeq ($(EXPLICITVERSION),)
+      # Generate the general dso if we aren't
+      # being asked to make just the specific version.
+      $(eval $(importlibtarget_unfrozen))
+    endif
+
+    $(eval $(importlibtarget_unfrozen_ver))
+  else
+    ifneq ($(DEFFILE),) # Frozen - use the def file and create .dso directly
+      define importlibtarget_func
+       $(IMPORTLIBTARGET_DSO): $(IMPORTLIBTARGETVERSIONED_DSO)
+	   $(call startrule,importlibtarget,FORCESUCCESS) \
+	   $(GNUCP) "$$<" "$$@" \
+	   $(call endrule,importlibtarget)
+      endef
+
+      ifeq ($(EXPLICITVERSION),)
+          # Generate the general dso if we aren't
+          # being asked to make just the specific version.
+          $(eval $(importlibtarget_func))
+      endif
+
+      define importlibtargetversioned_func
+        $(IMPORTLIBTARGETVERSIONED_DSO): $(ELF2E32) $(PREPPEDDEFFILE)
+	      $(call startrule,importlibversioned,FORCESUCCESS) \
+	      $(ELF2E32) --sid=0x$(if $(SID),$(SID),$(if $(UID3),$(UID3),0))  --version=$(VERSION)  	   \
+	 	  --definput="$(PREPPEDDEFFILE)" 				   \
+	 	  --dso=$$(call dblquote,$$@) 				   \
+	 	  --linkas=$(call dblquote,$(LINKASVERSIONED)) \
+	      $(call endrule,importlibversioned)
+      endef
+      $(eval $(importlibtargetversioned_func))
+    endif #  ifneq ($(DEFFILE),)
+  endif #  ifneq ($(EXPORTUNFROZEN),)
+endif #  ifneq ($(IMPORTLIBTARGET_DSO),)
+
+# ABIv1 .lib
+ifneq ($(IMPORTLIBTARGETVERSIONED_LIB),) # check that we haven't tried to specify this target already
+
+  # By Now we're committed to producing a target for this DSO so it's safe to
+  # set the marker that will prevent any further targets from being made.
+  $(eval $(BUILDMARKER_IMPORTLIBTARGET_LIB):=1)
+
+  define abiv1_generatelib
+
+    ifeq ($(EXPLICITVERSION),)
+      LIBRARY:: $(IMPORTLIBTARGETVERSIONED_LIB) $(IMPORTLIBTARGET_LIB)
+
+    else
+      LIBRARY:: $(IMPORTLIBTARGETVERSIONED_LIB)
+
+    endif
+
+    # If frozen, a prepped .def file is used as the basis for .lib creation
+    # If unfrozen, .lib files are based on the .def file generated by the final postlink
+    $(IMPORTLIBTARGETVERSIONED_LIB): $(if $(EXPORTUNFROZEN),$(E32TARGET),$(PREPPEDDEFFILE))
+	$(call startrule,importlibversioned_abiv1) \
+        if [ -f "$(EPOCROOT)/epoc32/tools/def2dll.pl" -a -f "$(if $(EXPORTUNFROZEN),$(call dblquote,$(GENERATED_DEFFILE)),$(PREPPEDDEFFILE))" ]; then \
+                 $(PERL) $(EPOCROOT)/epoc32/tools/def2dll.pl \
+		--path=$(IMPORTLIBPATH) \
+		--bldpath=$(INTERMEDIATEPATH) \
+		--import=$(notdir $(basename $(IMPORTLIBTARGETVERSIONED_LIB))) \
+		--deffile="$(if $(EXPORTUNFROZEN),$(call dblquote,$(GENERATED_DEFFILE)),$(PREPPEDDEFFILE))" \
+		--linkAs=$(call dblquote,$(LINKASVERSIONED)) \
+		--inter ; fi \
+	$(call endrule,importlibversioned_abiv1)
+
+    ifeq ($(EXPLICITVERSION),)
+      $(IMPORTLIBTARGET_LIB): $(IMPORTLIBTARGETVERSIONED_LIB)
+	$(call startrule,importlibtarget_abiv1) \
+	if [ -f $(EPOCROOT)/epoc32/tools/def2dll.pl ]; then $(GNUCP) "$$<" "$$@" ; fi \
+	$(call endrule,importlibtarget_abiv1)
+    endif
+  endef
+
+  $(eval $(abiv1_generatelib))
+endif #  ifneq ($(IMPORTLIBTARGET_LIB),)
+endif #  ($(or $(DEFFILE),$(EXPORTUNFROZEN)),)
+endif #  ifneq ($(IMPORTLIBRARYREQUIRED),)
+
+
+## POSTLINK ##################################################################
+
+# Set up the name of the exports file if this is a customdll
+EXPTARGET:=
+ifneq ($(DOPOSTLINK),)
+  ifneq ($(and $(or $(STATICLIBRARY),$(ARMLIBS),$(ARMRT)),$(DEFFILE)),)
+    EXPTARGET:=$(INTERMEDIATE_PLATFORM_PATH)/$(notdir $(VER_E32IMPORTLIBBASE)).exp
+  endif
+endif
+
+# Generating the import library is enough if TARGETTYPE=implib #############
+
+ifneq ($(DOPOSTLINK),)
+# Capabilities
+FINAL_CAPABILITIES:=$(if $(CAPABILITY),$(CAPABILITY),NONE)
+
+# Paging options for the old postlinker
+POSTLINKER_PAGEDOPTION:=--defaultpaged
+ifeq ($(PAGED),1)
+  POSTLINKER_PAGEDOPTION:=--paged
+endif
+ifeq ($(PAGED),0)
+  POSTLINKER_PAGEDOPTION:=--unpaged
+endif
+
+CLEANTARGETS:=$(CLEANTARGETS) $(E32TARGET)
+CLEANTARGETS:=$(CLEANTARGETS) $(GENERATED_DEFFILE)
+CLEANTARGETS:=$(CLEANTARGETS) $(GENERATED_DSO)
+
+endif # ifneq ($(DOPOSTLINK),)
+
+ifneq ($(TARGETTYPE),implib)
+
+## CUSTOM DLLS ###############################################################
+# exp file
+#
+# This tends to help getting exported objects
+# out of the arm libs and into custom dlls.
+
+ifneq ($(EXPTARGET),)
+ifeq ($(TARGET_$(EXPTARGET)),)
+# We only need one of these exptargets for UDEB and UREL
+TARGET_$(EXPTARGET):=1
+
+EXPTARGETASMFILE:=$(INTERMEDIATE_PLATFORM_PATH)/$(notdir $(VER_E32IMPORTLIBBASE)).s
+
+define e32expgen_func
+$(EXPTARGET): $(DEFFILE) $(ELF2E32)
+	$(call startrule,expgen) \
+	$(ELF2E32) \
+	   --definput=$$(call dblquote,$(DEFFILE)) \
+	   --dump=a \
+	   --output=$(call dblquote,$(EXPTARGETASMFILE)) && \
+	$(ASM) $(TARGET_ARCH_OPTION) $(AAPCS_OPTION) $(ASM_OUTPUT_OPTION) $$(call dblquote, $$@) $(EXPTARGETASMFILE) \
+	$(call endrule,expgen)
+endef
+
+$(eval $(e32expgen_func))
+CLEANTARGETS:=$(CLEANTARGETS) $(EXPTARGET) $(EXPTARGETASMFILE)
+endif
+endif
+
+
+
+
+## SOURCE FILES ##############################################################
+
+# Source files can be either C++ files (.cpp) or Assmbler-in-C++ files (.cia)
+# We have to split the two because they have the same link stage, the compile
+# stage is different for each.
+
+CPPFILEEXTENSIONS:=.cpp .CPP .Cpp .CPp .CpP .cPP .cpP .cPp .cc .CC \
+	.Cc .c++ .C++ .cxx .CXX .Cxx .cXx .CxX .CXx .cC .cXX .cxX
+CFILEEXTENSIONS:=.c .C
+CIAFILEEXTENSIONS:=.CIA .cia .Cia .cIa .cIA .ciA .CIa .CiA
+ASMFILEEXTENSIONS:=.s .S
+
+
+# Extract the CPP files from our sources
+CPPFILES:=$(call extractfilesoftype,$(CPPFILEEXTENSIONS),$(SOURCE))
+CFILES:=$(call extractfilesoftype,$(CFILEEXTENSIONS),$(SOURCE))
+ASMFILES:=$(call extractfilesoftype,$(ASMFILEEXTENSIONS),$(SOURCE))
+
+# Find out what assember-in-c files there are
+# If appropriate, work out what CPP files will be created from the assembler files
+CIAFILES:=$(call extractfilesoftype,$(CIAFILEEXTENSIONS),$(SOURCE))
+CIA_CPPFILES:=
+ifeq ($(TRANSFORM_CIA),1)
+  CIA_CPPFILES:=$(call relocatefiles,$(INTERMEDIATEPATH),$(call extractandmap,$(CIAFILEEXTENSIONS),_.cpp,$(CIAFILES)))
+else
+
+endif
+
+## LINK ######################################################################
+# Bring together all the .o files compiled from  .cpp, .c, .s and .cia files.
+# These files are stored in the "non-releasable" output diretory.
+
+define mapcpp2object
+$(call relocatefiles,$(INTERMEDIATEPATH),$(call extractandmap,$(CPPFILEEXTENSIONS),.o,$1))
+endef
+
+define mapc2object
+$(call relocatefiles,$(INTERMEDIATEPATH),$(call extractandmap,$(CFILEEXTENSIONS),.o,$1))
+endef
+
+define mapasm2object
+$(call relocatefiles,$(INTERMEDIATEPATH),$(call extractandmap,$(ASMFILEEXTENSIONS),.o,$1))
+endef
+
+define mapcia2object
+$(call relocatefiles,$(INTERMEDIATEPATH),$(call extractandmap,$(CIAFILEEXTENSIONS),_.o,$1))
+endef
+
+# Determine what object files will be linked by using the source files.
+CPPFILES_LINKOBJECTS:=$(call mapcpp2object,$(CPPFILES))
+CFILES_LINKOBJECTS:=$(call mapc2object,$(CFILES))
+ifeq ($(TRANSFORM_CIA),1) 
+  CIAFILES_LINKOBJECTS:=$(patsubst %_.cpp,%_.o,$(CIA_CPPFILES))
+else
+  CIAFILES_LINKOBJECTS:=$(call mapcia2object,$(CIAFILES))
+endif
+ASMFILES_LINKOBJECTS:=$(call mapasm2object,$(ASMFILES))
+
+# Try to link object files in the order in which the source files were specified.
+# This makes BC comparisons with non-Raptor builds easier.
+# Use the order of the source list to establish the order of the object files:
+LINKOBJECTS:=$(call relocatefiles,$(INTERMEDIATEPATH),$(SOURCE))
+# Replace the file extensions of the Source files with .o (or _.o for cia files) now
+# the list will contain the object files in the same order as the list of source files.
+LINKOBJECTS:=$(foreach FILE,$(LINKOBJECTS),$(basename $(FILE))$(if $(filter $(addprefix %,$(CIAFILEEXTENSIONS)),$(FILE)),_).o)
+
+ifneq ($(MULTIFILE_ENABLED),)
+MULTIFILEOBJECT:=$(INTERMEDIATEPATH)/$(TARGET).$(POSTLINKFILETYPE)_$(VARIANTTYPE)_multifileobject.o
+MULTIFILE_VIAFILE:=$(INTERMEDIATEPATH)/$(TARGET)_$(VARIANTTYPE)_multifile.via
+endif
+
+## Via file ####################################
+# list of all objects to be linked
+#
+VIAFILE:=$(INTERMEDIATEPATH)/$(TARGET)_$(VARIANTTYPE)_objects.via
+ifneq ($(GENERATELINKERFEEDBACK),)
+FEEDBACKFILE:=$(INTERMEDIATEPATH)/$(TARGET)_$(VARIANTTYPE)_feedback.fdb
+endif
+
+# The groupin10 macro allows us to construct a via file, 10 objects at a time
+# to avoid limits on argument lengths and sizes on Windows.
+# It expands to a list of commands, each of which is on a separate line.
+# This causes the shell to be invoked once for each line but each line should
+# be shorter than the maximum allowed by windows.
+define groupin10
+	$(if $1,@echo -e $(foreach L,$(wordlist 1,10,$1),"$(L)\\n") >>$(VIAFILE),)
+	$(if $1,$(call groupin10,$(wordlist 11,$(words $1),$1)),@true)
+endef
+
+################################################
+
+
+## Link-type selection:
+#	runtime static libraries link via AR
+ifneq ($(ARTARGET),)
+# Assuming that there are no libdeps in this case because this is probably one of the
+# Runtime libraries which has no deps.
+
+define artarget_func
+$(ARTARGET): $(if $(MULTIFILE_ENABLED),$(MULTIFILEOBJECT),$(LINKOBJECTS)) $(STDCPPTAGFILE)
+	$(if $(MULTIFILE_ENABLED),,@echo "$(STDCPPTAGFILE)" > $(VIAFILE);
+	$(call groupin10,$(LINKOBJECTS)) ;)
+	$(call startrule,ar,FORCESUCCESS) \
+	$$(call dblquote,$(AR)) $(ARCHIVER_CREATE_OPTION) $$@ $(if $(MULTIFILE_ENABLED),$(MULTIFILEOBJECT),$(COMMANDFILE_OPTION)$(VIAFILE)) \
+	$(if $(DUMPBCINFO),&& $(FROMELF) -v $$@  > $$@.elfdump,)  \
+	$(call endrule,ar)
+endef
+$(eval $(artarget_func))
+
+CLEANTARGETS:=$(CLEANTARGETS) $(VIAFILE) $(if $(DUMPBCINFO),$(ARTARGET).elfdump,)
+endif
+
+
+
+# Targettype is some type of DLL or EXE (or derivative)
+ifneq ($(LINK_TARGET),)
+
+located_ARMLIBS:=$(foreach L,$(ARMLIBS),$(wildcard $(RVCTLIB)/*/$(L)))
+located_STATICLIBRARIES:=$(foreach L,$(STATICLIBRARY),$(STATIC_LIBRARY_DIR)/$(L).lib)
+e32abiv2_LIBS:=$(EXPTARGET) $(LINKER_STUB_LIBRARY) $(if $(STATIC_RUNTIME_LIB),$(STATIC_RUNTIME_DIR)/$(STATIC_RUNTIME_LIB),) $(located_STATICLIBRARIES)
+# DLLS and EXEs - These objects are linked by a linker
+ifeq ($(ARMRT),)
+# Some of the runtime libraries do not set ARMRT because of a circular reference
+# problem; we need to stop these from linking to their own dso and not link to
+# the STATIC_LIBS_LIST.
+ifneq ($(findstring $(TARGET).dso,$(RUNTIME_LIBS_LIST)),)
+# (almost) ARM RUNTIME LIBS
+REDUCED_RUNTIME_LIBS_LIST:=$(subst $(TARGET).dso,,$(RUNTIME_LIBS_LIST))
+
+ifeq ($(VARIANTTYPE),udeb)
+  e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(IMPORTLIBPATH)/,$(LIBRARY_DEBUG)) $(addprefix $(RUNTIME_LIBS_PATH)/,$(REDUCED_RUNTIME_LIBS_LIST)) $(located_ARMLIBS)
+else
+  e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(IMPORTLIBPATH)/,$(LIBRARY)) $(addprefix $(RUNTIME_LIBS_PATH)/,$(REDUCED_RUNTIME_LIBS_LIST)) $(located_ARMLIBS)
+endif
+
+else
+# NORMAL
+#
+ifeq ($(VARIANTTYPE),udeb)
+  e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(IMPORTLIBPATH)/,$(LIBRARY_DEBUG))
+else
+  e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(IMPORTLIBPATH)/,$(LIBRARY))
+endif
+ifeq ($(HAS_DEDICATED_OP_NEWDEL_LIB),1)
+  e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(RUNTIME_LIBS_PATH)/,$(NEWLIB))
+endif
+e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(RUNTIME_LIBS_PATH)/,$(RUNTIME_LIBS_LIST)) $(addprefix $(STATIC_LIBS_PATH)/,$(STATIC_LIBS_LIST)) $(located_ARMLIBS)
+
+endif
+else
+# ARM RUNTIME LIBS
+ifeq ($(VARIANTTYPE),udeb)
+  e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(IMPORTLIBPATH)/,$(LIBRARY_DEBUG)) $(located_ARMLIBS)
+else
+  e32abiv2_LIBS:=$(e32abiv2_LIBS) $(addprefix $(IMPORTLIBPATH)/,$(LIBRARY)) $(located_ARMLIBS)
+endif
+endif
+
+# NOTE: the groupin10 macro must be used before a call to the "startrule" macro
+# because the code between startrule and endrule is packaged up into one
+# commandline which would defeat the purpose of groupin10.
+# This is undesirable because viafile generation commands appear
+# outside the relevant tags but it is also unavoidable.
+define linktarget_func
+## The actual link target, dependencies and build step
+$(E32TARGET): $(POSTLINKDEFFILE) $(ELF2E32) $(if $(MULTIFILE_ENABLED),$(MULTIFILEOBJECT) $(CIAFILES_LINKOBJECTS),$(LINKOBJECTS)) $(e32abiv2_LIBS) $(LINKER_ENTRYPOINT_LIBDEP) $(if $(SUPPORTS_STDCPP_NEWLIB),$(CHECKLIB)) $(if $(LINKERFEEDBACK_STAGE2),$(FEEDBACKFILE),) $(if $(HAVE_ORDERONLY),|,) $(EPOCROOT)/epoc32/build/TEM_LIB
+	$(if $(MULTIFILE_ENABLED),,@echo -n "" > $(VIAFILE);
+	$(call groupin10,$(LINKOBJECTS)) ;)
+	$(call startrule,linkandpostlink) \
+	$(if $(PERTURBSTARTTIME),$(RANSLEEP) $(PERTURBMSECS) ;,) \
+	$(if $(SUPPORTS_STDCPP_NEWLIB),$(if $(located_STATICLIBRARIES),$(CHECKLIB) $(CHECKLIB_TYPE) --elf $(call dblquote,$(located_STATICLIBRARIES)) &&,),) \
+	$(LD) $(LINKER_MISC_FLAGS) $(LINKER_DEFAULT_LIB_PATHS) $(SYMBIAN_LINK_FLAGS) $(if $(DEBUG_INFO),$(LINKER_DEBUG_OPTION),$(LINKER_NODEBUG_OPTION)) \
+	  $(if $(ARMLIBS),$(LD_WARNINGS_SUPPRESSION_ARMLIBS),) \
+	  $(SHARED_OBJECT_OPTION) $(SPLIT_OPTION) \
+	  $(RW_BASE) \
+	  $(LINKER_ARCH_OPTION) \
+	  $(SYMVER_OPTION) $(SO_NAME_OPTION)=$(call dblquote,$(LINKASVERSIONED)) \
+	  $(LINKER_ENTRYPOINT_SETTING) \
+	  -o $$(call dblquote,$(LINK_TARGET)) \
+	  $(if $(LTCG),$(LTCG_OPTION),) \
+	  $(LINKER_SYMBOLS_OPTION) $(LINKER_SYMBOLS_FILE_OPTION)=$(call dblquote,$(MAPFILE)) \
+  	  $(LINKEROPTION) \
+	  $(if $(MULTIFILE_ENABLED),$(call dblquote,$(MULTIFILEOBJECT) $(CIAFILES_LINKOBJECTS)),$(COMMANDFILE_OPTION)$(call dblquote,$(VIAFILE))) \
+      $(if $(GENERATELINKERFEEDBACK),$(FEEDBACK_OPTION)$(call dblquote,$(FEEDBACKFILE))) \
+	  $(if $(LINKER_ADD_STATIC_RUNTIME),$(if $(STATIC_RUNTIME_LIB),$(LINKER_GROUP_START_OPTION) $(STATIC_RUNTIME_DIR)/$(STATIC_RUNTIME_LIB) $(LINKER_GROUP_END_OPTION),)) \
+	  $(call dblquote,$(e32abiv2_LIBS)) $(LINKER_DEFAULT_LIBS) && \
+	  $(ELF2E32) \
+	  --sid=0x$(if $(SID),$(SID),$(if $(UID3),$(UID3),0)) \
+	  --version=$(VERSION) \
+	  --capability=$(FINAL_CAPABILITIES) \
+	  --linkas=$(call dblquote,$(LINKASVERSIONED)) \
+	  --fpu=$(if $(ARMFPU),$(ARMFPU),$(POSTLINKER_FPU_DEFAULT)) \
+	  --targettype=$(POSTLINKTARGETTYPE) \
+	  --output=$$(call dblquote,$$@) \
+	  --elfinput=$(call dblquote,$(LINK_TARGET)) \
+	  $(if $(UID1),--uid1=0x$(UID1),) \
+	  $(if $(UID2),--uid2=0x$(UID2),) \
+	  $(if $(UID3),--uid3=0x$(UID3),) \
+	  $(if $(VENDORID),--vid=0x$(VENDORID),) \
+	  $(if $(EXPTARGET),--customdlltarget,) \
+	  $(if $(ARMLIBS),--excludeunwantedexports,) \
+	  $(if $(EPOCALLOWDLLDATA),--dlldata,) \
+	  $(if $(EPOCPROCESSPRIORITY),--priority=$(EPOCPROCESSPRIORITY),) \
+	  $(if $(EPOCSTACKSIZE),--stack=0x$(EPOCSTACKSIZE),) \
+	  $(if $(EPOCHEAPSIZEMIN),--heap=0x$(EPOCHEAPSIZEMIN)$(CHAR_COMMA)0x$(EPOCHEAPSIZEMAX),) \
+	  $(if $(EPOCFIXEDPROCESS),--fixedaddress,) \
+	  $(if $(EPOCDATALINKADDRESS),--datalinkaddress=$(EPOCDATALINKADDRESS),) \
+	  $(if $(NAMEDSYMLKUP),--namedlookup,) \
+	  $(if $(SMPSAFE),--smpsafe,) \
+	  $(if $(POSTLINKDEFFILE),--definput=$(POSTLINKDEFFILE),) \
+	  $(if $(EXPORTUNFROZEN),--unfrozen,) \
+	  $(if $(AUTOEXPORTS),--sysdef=$(call dblquote,$(AUTOEXPORTS)),) \
+	  $(if $(CANIGNORENONCALLABLE), \
+	    $(if $(IMPORTLIBRARYREQUIRED),,--ignorenoncallable),) \
+	  $(if $(CANHAVEEXPORTS), --defoutput=$(call dblquote,$(GENERATED_DEFFILE)) --dso=$(GENERATED_DSO)) \
+	  $(if $(filter $(VARIANTTYPE),$(DEBUGGABLE)),--debuggable,) \
+	  $(if $(POSTLINKER_SUPPORTS_WDP), \
+	    --codepaging=$(PAGEDCODE_OPTION) --datapaging=$(PAGEDDATA_OPTION), \
+	    $(POSTLINKER_PAGEDOPTION)) \
+	  $(if $(NOCOMPRESSTARGET),--uncompressed, \
+	    $(if $(INFLATECOMPRESSTARGET),--compressionmethod=inflate, \
+	      $(if $(BYTEPAIRCOMPRESSTARGET),--compressionmethod=bytepair, \
+	        --compressionmethod=$(POSTLINKER_COMPRESSION_DEFAULT)))) \
+	  --libpath="$(call concat,$(PATHSEP)$(CHAR_SEMIC),$(strip $(RUNTIME_LIBS_PATH) $(STATIC_LIBS_PATH)))" \
+	  $(if $(SAVESPACE),$(if $(EXPORTUNFROZEN),,&& { $(GNURM) -rf $(INTERMEDIATEPATH); true; })) \
+	$(call endrule,linkandpostlink)
+
+$(MAPFILE): $(E32TARGET)
+$(LINK_TARGET): $(E32TARGET)
+endef
+ifneq ($(DOPOSTLINK),)
+$(eval $(linktarget_func))
+endif # ifneq ($(DOPOSTLINK),)
+
+CLEANTARGETS:=$(CLEANTARGETS) $(VIAFILE) $(if $(GENERATELINKERFEEDBACK),$(FEEDBACKFILE)) $(if $(MULTIFILE_ENABLED),$(MULTIFILEOBJECT))
+WHATRELEASE:=$(WHATRELEASE) $(MAPFILE)
+
+endif # if TARGETTYPE lib
+
+
+## Run trace compiler ##############################################
+ifeq ($(UID3),)
+ ifeq ($(UID2),)
+  USE_TRACE_COMPILER:=
+ else
+  UID_TC:=$(UID2)
+ endif
+else
+ UID_TC:=$(UID3)
+endif
+
+# USE_TRACE_COMPILER defaults to blank in Raptor config.
+# Users can turn TC on by setting it to 1 in user config.
+ifneq ($(USE_TRACE_COMPILER),)
+  # TARGETEXT is already set
+  include $(FLMHOME)/tracecompiler.mk
+  WHATRELEASE:=$(WHATRELEASE) $(TRACE_DICTIONARY) $(AUTOGEN_HEADER)
+endif
+
+CC_CPPONLY_ARGS:=$(SYMBIAN_CCFLAGS) $(if $(DEBUG_INFO),-g) $(DEBUG_FORMAT) \
+  $(RUNTIME_SYMBOL_VISIBILITY_OPTION) $(EXCEPTIONS) \
+  $(CC_WARNINGS_CONTROL_OPTION) $(CC_ERRORS_CONTROL_OPTION) \
+  $(TARGET_ARCH_OPTION) $(ENUM_OPTION) $(OWN_LIBRARY_OPTION) $(FPMODE_OPTION) \
+  $(EXPORT_VTBL_OPTION) $(NO_UNALIGNED_ACCESS) $(VFE_OPTION) $(AAPCS_OPTION) \
+  $(CPPONLYOPTION) $(INSTRUCTION_SET) \
+  $(if $(ALWAYS_BUILD_AS_ARM),$(ARM_INSTRUCTION_SET),$(THUMB_INSTRUCTION_SET) $(call makemacrodef,-D,$(COMPILER_THUMB_DEFINES))) \
+  $(COMPILER_FPU_OPTION)$(if $(ARMFPU),$(ARMFPU),$(COMPILER_FPU_DEFAULT))
+
+## COMPILE CPP Files #################################################################
+
+# For ARMCC we can compile all sourcefiles with one invocation
+# The pathprep macro is used to make sure that forward slashes in options
+# are not interpreted as being paths by CYGWIN on Windows.  On windows
+# pathprep makes a forward slash into two.
+
+# The majority of ARMCC arguments are common across all compiler invocations
+# Order is significant here in that OPTION_REPLACE here and in ABLD should
+# have the same impact
+CC_CORE_ARGS:=$(SYMBIAN_CCFLAGS) $(if $(DEBUG_INFO),-g) $(DEBUG_FORMAT) \
+  $(RUNTIME_SYMBOL_VISIBILITY_OPTION) $(EXCEPTIONS) \
+  $(CC_WARNINGS_CONTROL_OPTION) $(CC_ERRORS_CONTROL_OPTION) \
+  $(TARGET_ARCH_OPTION) $(ENUM_OPTION) $(OWN_LIBRARY_OPTION) $(FPMODE_OPTION) \
+  $(EXPORT_VTBL_OPTION) $(NO_UNALIGNED_ACCESS) $(VFE_OPTION) $(AAPCS_OPTION) \
+  $(COMPILE_ONLY_OPTION) $(INSTRUCTION_SET) \
+  $(if $(ALWAYS_BUILD_AS_ARM),$(ARM_INSTRUCTION_SET),$(THUMB_INSTRUCTION_SET) $(call makemacrodef,-D,$(COMPILER_THUMB_DEFINES))) \
+  $(COMPILER_FPU_OPTION)$(if $(ARMFPU),$(ARMFPU),$(COMPILER_FPU_DEFAULT))
+
+ifeq ($(STDCPP),1)
+SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$(call dblquote,$(STDCPP_INCLUDE)))
+endif
+
+define option_replace
+  # Process a single, combined, item of the form 'search<->replace' in order to modify the command line tool call
+  # We split this into its component arguments for use in substitutions
+  # Spaces will have been escaped elsewhere to maintain distinct words, so we resurrect these
+  # after the split.
+  SEARCH:=$(subst %20,$(CHAR_SPACE),$(word 1,$(subst <->,$(CHAR_SPACE),$(1))))
+  REPLACE:=$(subst %20,$(CHAR_SPACE),$(word 2,$(subst <->,$(CHAR_SPACE),$(1))))
+
+  # Depending on whether there's a wildcard in the search, we may require either a normal $(subst) or a $(patsubst)
+  PATSUBST:=$$(if $$(findstring %,$$(SEARCH)),1,)
+
+  ifeq ($$(PATSUBST),1)
+    CC_CORE_ARGS:=$$(patsubst $$(SEARCH),$$(REPLACE),$$(CC_CORE_ARGS))
+  else
+    CC_CORE_ARGS:=$$(subst $$(SEARCH),$$(REPLACE),$$(CC_CORE_ARGS))
+  endif
+endef
+$(foreach ITEM,$(OPTION_REPLACE_COMPILER),$(eval $(call option_replace,$(ITEM))))
+
+define e32abiv2_compile
+
+$(eval DEPENDFILENAME:=$(1).d)
+$(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
+
+# $4 is for language specific options (e.g. C++ vs C)
+$(1): $(2) $(PROJECT_META) $(if $(MULTIFILE_ENABLED),,$(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT)) $(if $(LINKERFEEDBACK_STAGE2),$(FEEDBACKFILE),) | $(if $(USE_TRACE_COMPILER),$(TRACE_MARKER),)  
+	$(call startrule,compile,,$(2))		\
+		$(if $(PERTURBSTARTTIME), $(RANSLEEP) $(PERTURBMSECS) ;,) \
+		$(if $(MULTIFILE_ENABLED), echo $(2) $(3) > $(MULTIFILE_VIAFILE) ;,) \
+		$(CC) $(LICENSERETRY_OPTION) \
+			$(CC_CORE_ARGS) \
+			$(OPTION_COMPILER) $(if $(MULTIFILE_ENABLED),$(4),$(3)) \
+			$(if $(LTCG),$(LTCG_OPTION),) \
+			$(if $(USE_PROFILER_FEEDBACK),--profile=$(call dblquote,$(ARM_PROFILER_FILE)),) \
+			$(call makemacrodef,-D,$(COMPILER_INTERWORK_DEFINES) $(CDEFS))				\
+			$(if $(PREINCLUDE),$(PREINCLUDE_OPTION) ,)$(call concat, $(PREINCLUDE_OPTION) ,$(call dblquote,$(PREINCLUDE)))\
+			$(if $(SET_ARMINC),$(if $(RVCTINC),$(COMPILER_SYSTEM_INCLUDE_OPTION)$(call dblquote,$(RVCTINC)),),)       \
+			$(COMPILER_SYSTEM_INCLUDE_OPTION)$$(call dblquote,$$(<D))                                                      \
+			$(if $(USERINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$(call dblquote,$(USERINCLUDE)))      \
+			$(if $(SYSTEMINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$(call dblquote,$(SYSTEMINCLUDE)))  \
+			$(if $(NOHIDEALL),--no_hide_all,) \
+			$(if $(NO_DEPEND_GENERATE),,$(DEPEND_OPTION) $(call dblquote,$(1).d)) \
+			$(if $(LINKERFEEDBACK_STAGE2),$(FEEDBACK_OPTION)$(call dblquote,$(FEEDBACKFILE))) \
+			$(if $(MULTIFILE_ENABLED),--multifile $(OUTPUT_OPTION) $(MULTIFILEOBJECT) \
+			--via $$(call dblquote, $(MULTIFILE_VIAFILE)),$(OUTPUT_OPTION) $$@ $$(call dblquote, $$<)) $(if $(USE_RVCT22_DELETE_WORKAROUND),$(RVCT22_DELETE_WORKAROUND)) \
+	$(call endrule,compile)
+
+ifeq ($(NO_DEPEND_GENERATE),)
+  CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
+endif
+
+ifneq ($(DEPENDFILE),)
+  ifeq ($(NO_DEPEND_INCLUDE),)
+    ifeq ($(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS))),)
+      -include $(DEPENDFILE)
+    endif
+  endif
+endif
+
+# individual source file compilation
+SOURCETARGET_$(call sanitise,$(2)): $(1)
+
+endef
+
+# Evaluate .cpp and .c files in one go for multifile, cannot do in separate steps since we have the same target.
+# This implementation means the .c files will always get put at the end of the .via file. Maybe there is a better way to do this?
+$(if $(MULTIFILE_ENABLED),$(eval $(call e32abiv2_compile,$(MULTIFILEOBJECT),$(CPPFILES),$(CFILES),$(CPP_LANG_OPTION))),$(foreach F,$(CPPFILES),$(eval $(call e32abiv2_compile,$(call mapcpp2object,$(F)),$(F),$(CPP_LANG_OPTION)))))
+$(if $(MULTIFILE_ENABLED),,$(foreach F,$(CFILES),$(eval $(call e32abiv2_compile,$(call mapc2object,$(F)),$(F),$(C_LANG_OPTION)))))
+ifneq ($(TRANSFORM_CIA),1)
+  $(if $(MULTIFILE_ENABLED),,$(foreach F,$(CIAFILES),$(eval $(call e32abiv2_compile,$(call mapcia2object,$(F)),$(F),$(CPP_LANG_OPTION) $(COMPILER_CIA_FLAGS)))))
+endif
+
+CLEANTARGETS:=$(CLEANTARGETS) $(if $(MULTIFILE_ENABLED),$(MULTIFILE_VIAFILE) $(MULTIFILEOBJECT),$(CPPFILES_LINKOBJECTS) $(CFILES_LINKOBJECTS) $(CIAFILES_LINKOBJECTS)) $(if $(GENERATELINKERFEEDBACK),$(FEEDBACKFILE))
+
+## Listing target ###################################################
+# Very similar to compile, apart from the extra flags passed to the
+# compile and different output options
+
+define map2listfile
+$(call relocatefiles,$(INTERMEDIATEPATH),$(call extractandmap,$(CPPFILEEXTENSIONS) $(CFILEEXTENSIONS),.lis,$1))
+endef
+
+
+define e32abiv2_cpponly
+# $1 is the sourcefile
+
+$(eval CPPONLYTARGET:=$(strip $(call extractandmap,$(CPPFILEEXTENSIONS) $(CFILEEXTENSIONS),.$(subst _,.,$(call sanitise,$(FULLVARIANTPATH))).pre,$1)))
+
+CPPONLY:: $(CPPONLYTARGET)
+
+$(CPPONLYTARGET): $(1) $(PROJECT_META)  $(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT)
+	$(call startrule,e32cpponly,,$(1))		\
+		$(if $(PERTURBSTARTTIME), $(RANSLEEP) $(PERTURBMSECS) ;,) \
+		$(CC) $(LICENSERETRY_OPTION) $(SYMBIAN_CCFLAGS) \
+			$(CC_CPPONLY_ARGS) \
+			$(OPTION_COMPILER) 						\
+			$(call makemacrodef,-D,$(COMPILER_INTERWORK_DEFINES) $(CDEFS))				\
+			$(if $(PREINCLUDE),$(PREINCLUDE_OPTION) ,)$(call concat, $(PREINCLUDE_OPTION) ,$(call dblquote,$(PREINCLUDE)))\
+			$(if $(SET_ARMINC),$(if $(RVCTINC),$(COMPILER_SYSTEM_INCLUDE_OPTION)$(call dblquote,$(RVCTINC)),),)       \
+			$(COMPILER_SYSTEM_INCLUDE_OPTION)$$(call dblquote,$$(<D))                                                   \
+			$(if $(USERINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$(call dblquote,$(USERINCLUDE)))      \
+			$(if $(SYSTEMINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$(call dblquote,$(SYSTEMINCLUDE)))  \
+			$(if $(NOHIDEALL),--no_hide_all,) \
+			$$(call dblquote, $$<) $(OUTPUT_OPTION) $$(@) $(if $(USE_RVCT22_DELETE_WORKAROUND),$(RVCT22_DELETE_WORKAROUND)) \
+	$(call endrule,e32cpponly)
+
+CLEANTARGETS:=$$(CLEANTARGETS) $(CPPONLYTARGET)
+endef
+
+ifneq ($(filter CPPONLY,$(call uppercase,$(MAKECMDGOALS))),)
+$(foreach F,$(CPPFILES) $(CFILES),$(eval $(call e32abiv2_cpponly,$(F))))
+endif
+
+define e32abiv2_listing
+# $1 is the sourcefile
+
+$(eval LISTINGTARGET:=$(strip $(call extractandmap,$(CPPFILEEXTENSIONS) $(CFILEEXTENSIONS),.$(subst _,.,$(call sanitise,$(FULLVARIANTPATH))).$(TARGET).$(TARGETEXT).lst,$1)))
+$(eval DEPENDFILENAME:=$(call map2listfile,$1).d)
+$(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
+
+
+LISTING:: $(LISTINGTARGET)
+
+$(LISTINGTARGET): $(1) $(PROJECT_META)  $(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT)
+	$(call startrule,e32listing,,$(1))		\
+		$(if $(PERTURBSTARTTIME), $(RANSLEEP) $(PERTURBMSECS) ;,) \
+		$(CC) $(LICENSERETRY_OPTION) $(SYMBIAN_CCFLAGS) \
+			$(CC_CORE_ARGS) \
+			$(LISTING_OPTION)		            	\
+			$(OPTION_COMPILER) 						\
+			$(call makemacrodef,-D,$(COMPILER_INTERWORK_DEFINES) $(CDEFS))				\
+			$(if $(PREINCLUDE),$(PREINCLUDE_OPTION) ,)$(call concat, $(PREINCLUDE_OPTION) ,$(call dblquote,$(PREINCLUDE)))\
+			$(if $(SET_ARMINC),$(if $(RVCTINC),$(COMPILER_SYSTEM_INCLUDE_OPTION)$(call dblquote,$(RVCTINC)),),)       \
+			$(COMPILER_SYSTEM_INCLUDE_OPTION)$$(call dblquote,$$(<D))                                                   \
+			$(if $(USERINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$(call dblquote,$(USERINCLUDE)))      \
+			$(if $(SYSTEMINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$(call dblquote,$(SYSTEMINCLUDE)))  \
+			$(if $(NOHIDEALL),--no_hide_all,) \
+			$(if $(NO_DEPEND_GENERATE),,$(DEPEND_OPTION) $(call dblquote,$(DEPENDFILENAME))) \
+			$$(call dblquote, $$<) $(OUTPUT_OPTION) $$(@) $(if $(USE_RVCT22_DELETE_WORKAROUND),$(RVCT22_DELETE_WORKAROUND)) \
+	$(call endrule,e32listing)
+
+CLEANTARGETS:=$$(CLEANTARGETS) $(LISTINGTARGET)
+
+ifeq ($(NO_DEPEND_GENERATE),))
+  CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
+endif
+
+ifneq ($(DEPENDFILE),)
+  ifeq ($(NO_DEPEND_INCLUDE),)
+    ifeq ($(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS))),)
+      -include $(DEPENDFILE)
+    endif
+  endif
+endif
+
+endef
+
+# No point at all in generating listing targetsif we aren't going to make them
+ifneq ($(filter LISTING,$(call uppercase,$(MAKECMDGOALS))),)
+$(foreach F,$(CPPFILES) $(CFILES),$(eval $(call e32abiv2_listing,$(F))))
+endif
+
+
+
+# Function to execute FREEZE ###########################################
+ifneq ($(SUPPORT_FREEZE),)
+
+# Fivespaces variable created to ensure a suitable gap of space characters
+# Is placed between the separate arguments. This fixes a problem in Cygwin, where
+# separate arguments are interpreted as a single argument when passed to bash
+FIVESPACES=$(BLANK)     $(BLANK)
+
+FREEZEGUARD:=TARGET_$(TARGET)_$(TARGETEXT)_$(IMPORTLIBPATH)_EFREEZE
+
+define e32freeze
+
+FREEZE:: $(1)
+	$(call startrule,freeze,,$(RESOLVED_DEFFILE)) \
+	$(EFREEZE) $(EFREEZE_REMOVE_OPTION) "$(RESOLVED_DEFFILE)" $(FIVESPACES) $(call dblquote,$(GENERATED_DEFFILE)) \
+	$(call endrule,freeze)
+endef
+
+# Only freeze once - udeb and urel cannot differ
+ifeq ($($(FREEZEGUARD)),)
+  # For most freezing activity we need the temporary .def file generated in the final post-link
+  # that lists the current exports - FREEZE can therefore be dependent on the final post-linked binary,
+  # with the side-effect that a build is triggered if someone tries to freeze without having built.
+  #
+  # However, there's one case where we don't want to be dependent on the post-linked binary in this way,
+  # and that's when (a) there are missing exports, (b) the user's aware of them and (c) they're deliberately freezing to
+  # remove them using EFREEZE's remove option.  Being dependent on the post-linked binary in this case, where ELF2E32
+  # actually fails to generate a final binary, would mean that the freeze would never happen and post-linking would
+  # just be continually re-attempted (to fail each time).
+  #
+  # So, as a special case, if the user is explicitly attempting to freeze and perform removals, we make FREEZE dependent
+  # on the temporary .def file instead.  This has no rule to actually make it, but gives a hint as to what is wrong if
+  # the users performs a freeze with remove without having explicitly built previously.
+  #
+  ifneq ($(EFREEZE_REMOVE_OPTION),)
+    $(eval $(call e32freeze,$(GENERATED_DEFFILE)))
+  else
+    $(eval $(call e32freeze,$(E32TARGET)))
+  endif
+  $(FREEZEGUARD):=1
+endif
+
+endif
+
+CLEANTARGETS:=$(CLEANTARGETS) $(if $(MULTIFILE_ENABLED),$(MULTIFILEOBJECT),$(CPPFILES_LINKOBJECTS) $(CFILES_LINKOBJECTS))
+
+## ASSEMBLER FILES ###################################################################
+# CIA VERSION      ############################################
+define mapcia2xxx
+$(call relocatefiles,$(INTERMEDIATEPATH),$(call extractandmap,$(CIAFILEEXTENSIONS),$2,$1))
+endef
+
+define e32abiv2_CIA2CPP
+
+$(eval e32abiv2_OFILE:=$(call mapcia2xxx,$(1),_.o))
+$(eval e32abiv2_PREFILE:=$(call mapcia2xxx,$(1),_.pre))
+$(eval e32abiv2_CPPFILE:=$(call mapcia2xxx,$(1),_.cpp))
+$(eval CLEANTARGETS:=$(CLEANTARGETS) $(e32abiv2_OFILE) $(e32abiv2_CPPFILE) $(e32abiv2_PREFILE))
+
+$(e32abiv2_OFILE): $(e32abiv2_CPPFILE) $(PROJECT_META)
+	$(call startrule,cia2cpp2o,,$(e32abiv2_CPPFILE)) \
+		$(if $(PERTURBSTARTTIME),$(RANSLEEP) $(PERTURBMSECS) ;,) \
+			$(CC) $(LICENSERETRY_OPTION) \
+			$(CC_CORE_ARGS) \
+			$(if $(LTCG),$(LTCG_OPTION),) \
+			$(OPTION_COMPILER) \
+			$(call makemacrodef,-D,$(COMPILER_INTERWORK_DEFINES) $(CDEFS) $(CIADEFS)) $(CPP_LANG_OPTION)      \
+	 		$(if $(USERINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$$(call dblquote,$(USERINCLUDE)))     \
+	 		$(if $(SYSTEMINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$$(call dblquote,$(SYSTEMINCLUDE))) \
+	 		$$(call dblquote, $$<) $(OUTPUT_OPTION) $$@ $(if $(USE_RVCT22_DELETE_WORKAROUND),$(RVCT22_DELETE_WORKAROUND)) \
+	$(call endrule,cia2cpp2o)
+
+
+# preprocessed CIA file to a CPP file
+$(e32abiv2_CPPFILE): $(e32abiv2_PREFILE)
+	$(call startrule,tranasm) \
+	$(if $(CPPFILT),CPPFILT="$(CPPFILT)",) \
+	$(TRANASM) --suppress-check --output="$$@" $$^ \
+	$(call endrule,tranasm)
+
+$(eval DEPENDFILENAME:=$(e32abiv2_PREFILE).d)
+$(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
+
+# preprocess the cia file
+$(eval e32abiv2_PREFILE_OPTIONS:= $(LICENSERETRY_OPTION) $(PREPROCESSOR_OPTION) $(CPP_OPTION) \
+       $(SYMBIAN_CCFLAGS) $(call makemacrodef,-D,$(COMPILER_INTERWORK_DEFINES) $(CDEFS) $(CIADEFS)) $(CPP_LANG_OPTION) \
+       $(if $(PREINCLUDE),$(PREINCLUDE_OPTION) ,)$$(call concat, $(PREINCLUDE_OPTION) ,$$(call dblquote,$(PREINCLUDE))) \
+       $(if $(USERINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$$(call dblquote,$(USERINCLUDE))) \
+       $(if $(SYSTEMINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$$(call dblquote,$(SYSTEMINCLUDE))) \
+       $(if $(ARMINC),$(if $(RVCTINC), $(COMPILER_SYSTEM_INCLUDE_OPTION)$$(call dblquote,$(RVCTINC)),),) )
+
+
+$(e32abiv2_PREFILE): $1 $(PROJECT_META) $(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT)
+	$(call startrule,cia2cpp,,$1) \
+	$(if $(PERTURBSTARTTIME),$(RANSLEEP) $(PERTURBMSECS) ;,) \
+	$(CC) $(e32abiv2_PREFILE_OPTIONS) $(OUTPUT_OPTION) $$@ $$(call dblquote,$1) $(if $(USE_RVCT22_DELETE_WORKAROUND),$(RVCT22_DELETE_WORKAROUND)) \
+	$(if $(NO_DEPEND_GENERATE),,&& $(CC) -M $(e32abiv2_PREFILE_OPTIONS) --depend_format=unix $(OUTPUT_OPTION) $$@ $$(call dblquote,$1) > $(call dblquote,$(e32abiv2_PREFILE).d)) \
+	$(call endrule,cia2cpp)
+
+ifeq ($(NO_DEPEND_GENERATE),)
+  CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
+endif
+
+ifneq ($(DEPENDFILE),)
+  ifeq ($(NO_DEPEND_INCLUDE),)
+    ifeq ($(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS))),)
+      -include $(DEPENDFILE)
+    endif
+  endif
+endif
+
+endef
+
+# Create a rule for each cia file
+ifeq ($(TRANSFORM_CIA),1)
+  $(eval $(foreach e32abiv2_RULE,$(CIAFILES),$(call e32abiv2_CIA2CPP,$(e32abiv2_RULE))))
+endif
+
+# Pure assembler (.s files) ################################
+
+e32abiv2_asm_OPTIONS:=$(LICENSERETRY_OPTION) \
+  $(CC_CORE_ARGS) \
+  $(OPTION_COMPILER) \
+  $(call makemacrodef,-D,$(COMPILER_INTERWORK_DEFINES) $(CDEFS)) \
+  $(if $(USERINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$$(call dblquote,$(USERINCLUDE)))     \
+  $(if $(SYSTEMINCLUDE),$(COMPILER_SYSTEM_INCLUDE_OPTION),)$$(call concat, $(COMPILER_SYSTEM_INCLUDE_OPTION),$$(call dblquote,$(SYSTEMINCLUDE)))
+
+# note that the --no_rtti option cannot be passed with the -M option
+# so forcibly remove it when generating ASM dependencies.
+#
+define e32abiv2_asm
+
+$(eval DEPENDFILENAME:=$(1).d)
+$(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
+
+$(1): $(2) $(PROJECT_META) $(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT)
+	$(call startrule,asmcompile,,$(2)) \
+		$(if $(PERTURBSTARTTIME),$(RANSLEEP) $(PERTURBMSECS) ;,) \
+		$(CC) $(e32abiv2_asm_OPTIONS) \
+		$(if $(NO_DEPEND_GENERATE),,$(DEPEND_OPTION) $(call dblquote,$(DEPENDFILENAME))) \
+	 	$$(call dblquote, $$<) $(OUTPUT_OPTION) $$@ $(if $(USE_RVCT22_DELETE_WORKAROUND),$(RVCT22_DELETE_WORKAROUND)) \
+	$(call endrule,asmcompile)
+ifeq ($(NO_DEPEND_GENERATE),)
+	$(call startrule,asmdependencies) \
+		$(CC) -M $(subst --no_rtti,,$(e32abiv2_asm_OPTIONS)) --depend_format=unix \
+	  	$(OUTPUT_OPTION) $$@ $$(call dblquote,$2) > $(call dblquote,$(DEPENDFILENAME)) $(if $(USE_RVCT22_DELETE_WORKAROUND),$(RVCT22_DELETE_WORKAROUND)) \
+	$(call endrule,asmdependencies)
+endif
+
+ifeq ($(NO_DEPEND_GENERATE),)
+  CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
+endif
+
+ifneq ($(DEPENDFILE),)
+  ifeq ($(NO_DEPEND_INCLUDE),)
+    ifeq ($(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS))),)
+      -include $(DEPENDFILE)
+    endif
+  endif
+endif
+
+CREATABLEPATHS:=$$(CREATABLEPATHS) $(INTERMEDIATEPATH)
+
+endef
+
+$(eval $(foreach F,$(ASMFILES), $(call e32abiv2_asm,$(call mapasm2object,$(F)),$(F))))
+CLEANTARGETS:=$(CLEANTARGETS) $(ASMFILES_LINKOBJECTS)
+
+endif # ifneq ($(TARGETTYPE),implib)
+
+
+########################## Build ROMFILE target ############################
+EPOC_ROOT:=$(patsubst %/,%,$(EPOCROOT))
+TOBLDINF:=$(dir $(subst :,,$(subst $(EPOC_ROOT)/,,$(COMPONENT_META))))
+
+# Only build ROMFILE if asked
+ifneq ($(filter ROMFILE,$(call uppercase,$(MAKECMDGOALS))),)
+    ifeq ($(ROMFILE_$(call sanitise,$(TARGET).$(REQUESTEDTARGETEXT))),)
+        ROMFILE_$(call sanitise,$(TARGET).$(REQUESTEDTARGETEXT)):=1
+        ROMDIR:=$(EPOC_ROOT)/epoc32/rom/$(TOBLDINF)
+
+        # Default values
+        ROMFILETYPE:=file
+        ROMFILE:=$(TARGET).$(REQUESTEDTARGETEXT)
+        ROMPATH:=sys/bin/
+        ROMDECORATIONS:=
+        ROMFILETYPE_RAM:=data
+        ROMFILE_RAM:=$(TARGET).$(REQUESTEDTARGETEXT)
+        ROMPATH_RAM:=sys/bin/
+        BUILDROMTARGET:=1
+        ABIDIR:=MAIN
+
+        $(eval $(call DoRomSet))
+
+        ifneq ($(EPOCFIXEDPROCESS),)
+            ROMDECORATIONS:=$(ROMDECORATIONS) fixed
+        endif
+        ifeq ($(PAGED),1)
+            ROMDECORATIONS:=$(ROMDECORATIONS) paged
+        endif
+        ifeq ($(PAGED),0)
+            ROMDECORATIONS:=$(ROMDECORATIONS) unpaged
+        endif
+
+
+        DATATEXT:=
+        ifeq ($(TESTCODE),TRUE)
+        	# Add 'TEST' to the .iby filename
+        	ROMTEST:=test
+            ifeq ($(TEST_OPTION),BOTH)
+                DATATEXT:="data=/epoc32/data/z/test/$(MODULE)/$(VARIANTPLATFORM).auto.bat test/$(MODULE).auto.bat"\n"data=/epoc32/data/z/test/$(MODULE)/$(VARIANTPLATFORM).manual.bat test/$(MODULE).manual.bat"
+            else
+                ifneq ($(TEST_OPTION),NONE)
+                    DATATEXT:="data=/epoc32/data/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TEST_OPTION).bat test/$(MODULE).$(TEST_OPTION).bat"
+                endif
+            endif
+        endif
+
+        # ROMTARGET
+        ifneq ($(ROMTARGET),)
+            ifneq ($(words $(ROMTARGET)),1)
+                ROMTARGETALL:=$(ROMTARGET)
+                ROMTARGET:=$(word 1,$(ROMTARGET))
+            endif
+
+            ifeq ($(ROMTARGET),<none>)
+                BUILDROMTARGET:=
+            else
+                ifneq ($(ROMTARGET),+)
+                    ifneq ($(notdir $(ROMTARGET)),)
+                        ROMFILE:=$(notdir $(ROMTARGET))
+                    endif
+                    ifneq ($(dir $(ROMTARGET)),./)
+                        ROMPATH:=$(dir $(ROMTARGET))
+                    endif
+                endif
+            endif
+        endif
+    endif
+
+    ROMFILENAME:=$(ROMDIR)$(PLATFORM)$(ROMTEST).iby
+
+    # RAMTARGET
+    ifneq ($(RAMTARGET),)
+        ROMDECORATIONS_RAM:=" attrib=r"
+        ifneq ($(RAMTARGET),+)
+            ifneq ($(notdir $(RAMTARGET)),)
+                ROMFILE_RAM:=$(notdir $(RAMTARGET))
+            endif
+            ifneq ($(dir $(RAMTARGET)),./)
+                ROMPATH_RAM:=$(dir $(RAMTARGET))
+            endif
+        endif
+    endif
+
+    define BuildRomfileTarget
+        $(ALLTARGET)::ROMFILE
+        ROMFILE::
+	        $(call startrule,rombuild)	\
+	        $(GNUMKDIR) -p $(ROMDIR) \
+            $(if $(ROMFILE_CREATED_$(TOBLDINF)),,&& echo -e "// $(subst $(EPOC_ROOT)/,,$(ROMFILENAME))\n//\n$(DATATEXT)" > $(ROMFILENAME)) \
+            $(if $(BUILDROMTARGET),&& echo "$(ROMFILETYPE)=/epoc32/release/##$(ABIDIR)##/##BUILD##/$(TARGET).$(REQUESTEDTARGETEXT)   $(1)$(ROMDECORATIONS)" >> $(ROMFILENAME))	\
+	        $(if $(RAMTARGET),&& echo "$(ROMFILETYPE_RAM)=/epoc32/release/##$(ABIDIR)##/##BUILD##/$(TARGET).$(REQUESTEDTARGETEXT)   $(ROMPATH_RAM)$(ROMFILE_RAM)$(ROMDECORATIONS_RAM)" >> $(ROMFILENAME))	\
+	        $(call endrule,buildromfiletarget)
+    endef
+
+    # When VARIANTTYPE changes, romfile is finished,
+    # apart from if this is a new component......
+    ifneq ($(PREVIOUSVARIANTTYPE),)
+        ifneq ($(VARIANTTYPE),$(PREVIOUSVARIANTTYPE))
+            ifneq ($(ROMFILE_CREATED_$(TOBLDINF)),)
+                ROMFILEFINISHED:=1
+            else
+                ROMFILEFINISHED:=
+            endif
+        endif
+    endif
+
+    # When romfile is finished, don't continue to add to it
+    ifeq ($(ROMFILEFINISHED),)
+        $(eval $(call BuildRomfileTarget,$(ROMPATH)$(ROMFILE)))
+    endif
+
+    # Don't allow romfile to be recreated for every MMP
+    ifeq ($(ROMFILE_CREATED_$(TOBLDINF)),)
+        ROMFILE_CREATED_$(TOBLDINF):=1
+    endif
+
+    # Build other ROMTARGETs if there is more than one
+    ifneq ($(ROMTARGETALL),)
+        RAMTARGET:=
+        $(foreach ROMTARGET,$(wordlist 2,$(words $(ROMTARGETALL)),$(ROMTARGETALL)),$(eval $(call BuildRomfileTarget,$(ROMTARGET))))
+        ROMTARGETALL:=
+    endif
+
+    # Keep track of variant type while romfile is being created
+    PREVIOUSVARIANTTYPE:=$(VARIANTTYPE)
+
+    WHATRELEASE:=$(WHATRELEASE) $(ROMFILENAME)
+endif
+
+# Deal with test code batch files generation.
+ifneq ($(TESTPATH),)
+
+    CREATABLEPATHS:=$(CREATABLEPATHS) $(EPOCROOT)/epoc32/data/z/test/
+    $(eval $(call MakeTestBatchFiles,$(TARGET),$(EPOCROOT)/epoc32/data/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH)))
+    BATCHFILE_CREATED_$(EPOCROOT)/epoc32/data/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH):=1
+    TARGET_CREATED_$(EPOCROOT)/epoc32/data/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH)_$(TARGET):=1
+    WHATRELEASE:=$(WHATRELEASE) $(EPOCROOT)/epoc32/data/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH)
+endif
+
+###################### End of Build ROMFILE target ######################
+
+# Feature Variation requires a .vmap file to be created for each binary
+#
+ifneq ($(FEATUREVARIANTNAME),)
+ifneq ($(E32TARGET),)
+
+OUTPUTVMAP:=$(E32TARGET).vmap
+WHATRELEASE:=$(WHATRELEASE) $(OUPUTVMAP)
+
+TARGET:: $(OUTPUTVMAP)
+VMAPNEEDS:=$(E32TARGET) $(SOURCE) $(PROJECT_META)
+
+BV_SOURCELIST:=$(addprefix -s ,$(SOURCE) $(PROJECT_META))
+BV_FEATURELIST:=$(addprefix -f ,$(FEATURELISTFILES))
+BV_USER_INCLUDES:=$(addprefix -u ,$(USERINCLUDE))
+BV_SYSTEM_INCLUDES:=$(addprefix -x ,$(SYSTEMINCLUDE))
+
+# translate double quoted macros because $(shell) messes them up in some make engines
+BV_MACROLIST:=$(COMPILER_INTERWORK_DEFINES) $(CDEFS) $(if $(ALWAYS_BUILD_AS_ARM),,$(COMPILER_THUMB_DEFINES))
+BV_DEFINES:=$(call makemacrodef,-D,$(subst ",__SBS__QUOTE__,$(BV_MACROLIST)))
+
+# the script to generate our .vmap file and hash value
+VMAPCOMMAND:=$(CREATEVMAP) -o $(OUTPUTVMAP) $(BV_FEATURELIST) $(BV_DEFINES) -p $(PREINCLUDE) $(BV_SOURCELIST) $(BV_USER_INCLUDES) $(BV_SYSTEM_INCLUDES) -c $(CREATEVMAPCPP)
+
+# a recipe to create the .vmap from the "sources" with the createvmap script
+$(call raptor_recipe,createvmap,$(OUTPUTVMAP),$(VMAPNEEDS),$(VMAPCOMMAND))
+
+endif # E32TARGET != ""
+endif # FEATUREVARIANTNAME != ""
+
+########################### CONCLUSION ###################################
+
+# make the output directories while reading makefile - some build engines prefer this
+$(call makepath,$(CREATABLEPATHS))
+
+## Clean up
+$(call raptor_clean,$(CLEANTARGETS))
+
+# For the --what option and the log file
+$(call raptor_release,$(filter-out %.sym,$(WHATRELEASE)))
+
+endif # DOBUILD
+
+## The End
+
--- a/sbsv2/raptor/lib/flm/e32abiv2ani.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2ani.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,56 +1,65 @@
-# 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:
-# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
-# Build a window server animation DLL. 
-# 
-#
-
-ifeq ($(TARGETTYPE),ani)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-# What we need to build a DLL
-CANHAVEEXPORTS:=1
-POSTLINKTARGETTYPE:=ANI
-POSTLINKFILETYPE:=ani
-DOPOSTLINK:=1
-AUTOEXPORTS:=_Z15CreateCAnimDllLv,1;
-DEFFILE:=
-
-# Determine what kind of entrypoint option to set
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edll.lib
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Dll $(LINKER_ENTRYPOINT_DECORATION) $(call dblquote,$(STATIC_RUNTIME_DIR)/edll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
-STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
-CANIGNORENONCALLABLE:=1
-
-UID2:=10003b22
-
-
-# We are appending to CDEFS but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS)
-CDEFS:=$(CDEFS) __DLL__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2dll.flm called with wrong TARGETTYPE (should be 'ani' but is '$(TARGETTYPE)'))
-endif
-
+# 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:
+# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
+# Build a window server animation DLL. 
+# 
+#
+
+ifeq ($(TARGETTYPE),ani)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+# What we need to build a DLL
+CANHAVEEXPORTS:=1
+POSTLINKTARGETTYPE:=ANI
+POSTLINKFILETYPE:=ani
+DOPOSTLINK:=1
+AUTOEXPORTS:=_Z15CreateCAnimDllLv,1;
+
+
+# Determine what kind of entrypoint option to set
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edll.lib
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Dll $(LINKER_ENTRYPOINT_DECORATION)$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/edll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
+STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
+CANIGNORENONCALLABLE:=1
+
+# Fixed export TARGETTYPEs should only reference a .def file if an explicit DEFFILE statement is present in the .mmp file
+ifneq ($(DEFFILEKEYWORD),)
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+ifeq ($(NOEXPORTLIBRARY),)
+IMPORTLIBRARYREQUIRED:=1
+endif
+endif
+
+UID2:=10003b22
+
+
+# We are appending to CDEFS but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS)
+CDEFS:=$(CDEFS) __DLL__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error $e32abiv2dll.flm called with wrong TARGETTYPE (should be 'ani' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/e32abiv2defaults.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2defaults.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,91 +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: 
-# e32abiv2defaults.flm
-# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
-#
-
-# This is for variables that are not set in an FLM call but
-# only in e32abiv2 flms.  
-
-AUTOEXPORTS:=
-CANHAVEEXPORTS:=
-CANIGNORENONCALLABLE:=
-DOPOSTLINK:=
-IMPORTLIBRARYREQUIRED:=
-LINKER_ENTRYPOINT_LIBDEP:=
-LINKER_ENTRYPOINT_SETTING:=
-LINKER_STUB_LIBRARY:=
-NAMEDSYMLKUP:=
-POSTLINKDEFFILE:=
-POSTLINKFILETYPE:=
-POSTLINKTARGETTYPE:=
-STATIC_RUNTIME_LIB:=
-SUPPORT_FREEZE:=
-NOHIDEALL:=
-DEFAULT_NEWLIB:=$(DEFAULT_SYMBIAN_NEWLIB)
-
-
-# Reset these variables as they change for every single target type
-# LINKER_ENTRYPOINT_ADORNMENT will be blank for GCCE; for RVCT it will look like "(uc_exe_.o)"
-# LINKER_ENTRYPOINT_DECORATION will be blank for RVCT; for GCCE it will look like "-u _E32Startup"
-
-LINKER_ENTRYPOINT_ADORNMENT:=
-LINKER_ENTRYPOINT_DECORATION:=
-
-# For GCCE
-ifeq ($(TOOLCHAIN),GCCE)
-LINKER_ENTRYPOINT_DECORATION:=$(if $(call isoneof,$(TARGETTYPE),exexp exe),-u _E32Startup,-u _E32Dll)
-endif
-
-# For RVCT
-ifeq ($(TOOLCHAIN),RVCT)
-  ifeq ($(call isoneof,$(TARGETTYPE),exe stdexe),1) # isoneof returns 1 if true, empty string if false
-	LINKER_ENTRYPOINT_ADORNMENT:=(uc_exe_.o)
-  endif
-
-  ifeq ($(call isoneof,$(TARGETTYPE),ani textnotifier2 stddll plugin fsy pdl dll),1)
-	LINKER_ENTRYPOINT_ADORNMENT:=(uc_dll_.o)
-  endif
-
-  ifeq ($(call isoneof,$(TARGETTYPE),var var2),1)
-	LINKER_ENTRYPOINT_ADORNMENT:=(v_entry_.o)
-  endif
-
-  ifeq ($(call isoneof,$(TARGETTYPE),ldd pdd),1)
-	LINKER_ENTRYPOINT_ADORNMENT:=(D_ENTRY_.o)
-  endif
-
-  ifeq ($(TARGETTYPE),kext)
-	LINKER_ENTRYPOINT_ADORNMENT:=(X_ENTRY_.o)
-  endif
-
-  ifeq ($(TARGETTYPE),kdll)
-	LINKER_ENTRYPOINT_ADORNMENT:=(L_ENTRY_.o)
-  endif
-endif
-
-# "OPTION" metadata from the front-end can potentially be supplied simultaneously for both GCCE and RVCT,
-# so we need to make a decision on what we make use of based on the TOOLCHAIN in use.
-# Currently we only support changes to RVCT tool calls.
-
-LINKEROPTION:=
-OPTION_COMPILER:=
-OPTION_REPLACE_COMPILER:=
-
-ifeq ($(TOOLCHAIN),RVCT)
-  LINKEROPTION:=$(LINKEROPTION_ARMCC)
-  OPTION_COMPILER:=$(OPTION_ARMCC)
-  OPTION_REPLACE_COMPILER:=$(OPTION_REPLACE_ARMCC)
-endif
+#
+# 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: 
+# e32abiv2defaults.flm
+# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
+#
+
+# This is for variables that are not set in an FLM call but
+# only in e32abiv2 flms.  
+
+AUTOEXPORTS:=
+CANHAVEEXPORTS:=
+CANIGNORENONCALLABLE:=
+DOPOSTLINK:=
+IMPORTLIBRARYREQUIRED:=
+LINKER_ENTRYPOINT_LIBDEP:=
+LINKER_ENTRYPOINT_SETTING:=
+LINKER_STUB_LIBRARY:=
+NAMEDSYMLKUP:=
+POSTLINKDEFFILE:=
+POSTLINKFILETYPE:=
+POSTLINKTARGETTYPE:=
+STATIC_RUNTIME_LIB:=
+SUPPORT_FREEZE:=
+NOHIDEALL:=
+DEFAULT_NEWLIB:=$(DEFAULT_SYMBIAN_NEWLIB)
+
+
+# Reset these variables as they change for every single target type
+# LINKER_ENTRYPOINT_ADORNMENT will be blank for GCCE; for RVCT it will look like "(uc_exe_.o)"
+# LINKER_ENTRYPOINT_DECORATION will be blank for RVCT; for GCCE it will look like "-u _E32Startup"
+# LINKER_SEPARATOR is a comma for GCCE as g++ is used for linking; for RVCT is should be a space, but
+# as make strips trailing spaces, we use the CHAR_SPACE variable.
+
+LINKER_ENTRYPOINT_ADORNMENT:=
+LINKER_ENTRYPOINT_DECORATION:=
+LINKER_SEPARATOR:=
+
+# For GCCE
+ifeq ($(TOOLCHAIN),GCCE)
+LINKER_ENTRYPOINT_DECORATION:=$(if $(call isoneof,$(TARGETTYPE),exexp exe),-Wl$(CHAR_COMMA)-u$(CHAR_COMMA)_E32Startup,-Wl$(CHAR_COMMA)-u$(CHAR_COMMA)_E32Dll)
+LINKER_SEPARATOR:=$(CHAR_COMMA)
+endif
+
+# For RVCT
+ifeq ($(TOOLCHAIN),RVCT)
+  ifeq ($(call isoneof,$(TARGETTYPE),exe stdexe),1) # isoneof returns 1 if true, empty string if false
+	LINKER_ENTRYPOINT_ADORNMENT:=(uc_exe_.o)
+  endif
+
+  ifeq ($(call isoneof,$(TARGETTYPE),ani textnotifier2 stddll plugin plugin3 fsy pdl dll pdll),1)
+	LINKER_ENTRYPOINT_ADORNMENT:=(uc_dll_.o)
+  endif
+
+  ifeq ($(call isoneof,$(TARGETTYPE),var var2),1)
+	LINKER_ENTRYPOINT_ADORNMENT:=(v_entry_.o)
+  endif
+
+  ifeq ($(call isoneof,$(TARGETTYPE),ldd pdd),1)
+	LINKER_ENTRYPOINT_ADORNMENT:=(D_ENTRY_.o)
+  endif
+
+  ifeq ($(TARGETTYPE),kext)
+	LINKER_ENTRYPOINT_ADORNMENT:=(X_ENTRY_.o)
+  endif
+
+  ifeq ($(TARGETTYPE),kdll)
+	LINKER_ENTRYPOINT_ADORNMENT:=(L_ENTRY_.o)
+  endif
+LINKER_SEPARATOR:=$(CHAR_SPACE)
+endif
+
+# "OPTION" metadata from the front-end can potentially be supplied simultaneously for both GCCE and RVCT,
+# so we need to make a decision on what we make use of based on the TOOLCHAIN in use.
+# Currently we only support changes to RVCT tool calls.
+
+LINKEROPTION:=
+OPTION_COMPILER:=
+OPTION_REPLACE_COMPILER:=
+
+ifeq ($(TOOLCHAIN),RVCT)
+  LINKEROPTION:=$(LINKEROPTION_ARMCC)
+  OPTION_COMPILER:=$(OPTION_ARMCC)
+  OPTION_REPLACE_COMPILER:=$(OPTION_REPLACE_ARMCC)
+endif
+
+# "ARMFPU" overrides for 'fpu-ness' in compiler and postlinker calls in .mmp files are currently only
+# supported for RVCT-based builds, GCCE builds always make use of the interface defined defaults.
+ifeq ($(TOOLCHAIN),GCCE)
+  ARMFPU:=
+endif
--- a/sbsv2/raptor/lib/flm/e32abiv2dll.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2dll.flm	Wed Jun 23 16:56:47 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:
-# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
-# Build an e32 DLL (Dynamic Link Library)
-# 
-#
-
-ifeq ($(TARGETTYPE),dll)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-# What we need to build a DLL
-ifeq ($(NOEXPORTLIBRARY),)
-IMPORTLIBRARYREQUIRED:=1
-endif
-POSTLINKDEFFILE:=$(DEFFILE)
-SUPPORT_FREEZE:=1
-
-# Default Linker settings for this target type
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edll.lib
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Dll $(LINKER_ENTRYPOINT_DECORATION) $(call dblquote,$(STATIC_RUNTIME_DIR)/edll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
-STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
-
-
-# Default Postlinker settings
-CANHAVEEXPORTS:=1
-POSTLINKTARGETTYPE:=DLL
-POSTLINKFILETYPE:=dll
-DOPOSTLINK:=1
-CANIGNORENONCALLABLE:=1
-
-# Use the general EABI FLM 
-# We are appending to CDEFS but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS)
-CDEFS:=$(CDEFS) __DLL__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2dll.flm called with wrong TARGETTYPE (should be 'dll' but is '$(TARGETTYPE)'))
-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:
+# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
+# Build an e32 DLL (Dynamic Link Library)
+# 
+#
+
+ifeq ($(TARGETTYPE),dll)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+# What we need to build a DLL
+ifeq ($(NOEXPORTLIBRARY),)
+IMPORTLIBRARYREQUIRED:=1
+endif
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+
+# Default Linker settings for this target type
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edll.lib
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Dll $(LINKER_ENTRYPOINT_DECORATION)$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/edll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
+STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
+
+
+# Default Postlinker settings
+CANHAVEEXPORTS:=1
+POSTLINKTARGETTYPE:=DLL
+POSTLINKFILETYPE:=dll
+DOPOSTLINK:=1
+CANIGNORENONCALLABLE:=1
+
+# Use the general EABI FLM 
+# We are appending to CDEFS but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS)
+CDEFS:=$(CDEFS) __DLL__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error e32abiv2dll.flm called with wrong TARGETTYPE (should be 'dll' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/e32abiv2exe.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2exe.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,49 +1,51 @@
-# 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:
-# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
-# Build an e32 EXE
-# 
-#
-
-# What we need to build an EXE
-
-ifeq ($(TARGETTYPE),exe)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-POSTLINKTARGETTYPE:=EXE
-POSTLINKFILETYPE:=exe
-DOPOSTLINK:=1
-# Determine what kind of entrypoint option to set
-LINKER_STUB_LIBRARY:=
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/$(if $(FIRSTLIB),$(FIRSTLIB),eexe.lib)
-
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Startup $(LINKER_ENTRYPOINT_DECORATION) $(call dblquote,$(STATIC_RUNTIME_DIR)/$(if $(FIRSTLIB),$(FIRSTLIB),eexe.lib)$(LINKER_ENTRYPOINT_ADORNMENT)) 
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
-
-MAKEDEFFILE:=
-
-$(call vsave,CDEFS)
-CDEFS:=$(CDEFS) __EXE__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2exe.flm called with wrong TARGETTYPE (should be 'exe' but is '$(TARGETTYPE)'))
-endif
-
+# 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:
+# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
+# Build an e32 EXE
+# 
+#
+
+# What we need to build an EXE
+
+ifeq ($(TARGETTYPE),exe)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+POSTLINKTARGETTYPE:=EXE
+POSTLINKFILETYPE:=exe
+DOPOSTLINK:=1
+# Determine what kind of entrypoint option to set
+LINKER_STUB_LIBRARY:=
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/$(if $(FIRSTLIB),$(FIRSTLIB),eexe.lib)
+
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Startup $(LINKER_ENTRYPOINT_DECORATION)$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/$(if $(FIRSTLIB),$(FIRSTLIB),eexe.lib)$(LINKER_ENTRYPOINT_ADORNMENT)) 
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+ifeq ($(EPOCNESTEDEXCEPTIONS),)
+  STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
+else
+  STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB_NESTED_EXCEPTIONS)
+endif
+
+$(call vsave,CDEFS)
+CDEFS:=$(CDEFS) __EXE__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error $e32abiv2exe.flm called with wrong TARGETTYPE (should be 'exe' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/e32abiv2exexp.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2exexp.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,83 +1,83 @@
-# 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:
-# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
-# Build an e32 EXE with exports
-# 
-#
-
-ifeq ($(TARGETTYPE),exexp)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-# What we need to build an EXEXP
-CANHAVEEXPORTS:=1
-POSTLINKTARGETTYPE:=EXEXP
-POSTLINKFILETYPE:=exe
-DOPOSTLINK:=1
-EPOCALLOWDLLDATA:=1
-CANIGNORENONCALLABLE:=1
-
-$(call vsave,CDEFS)
-# Determine what kind of entrypoint option to set
-FIRSTLIB_OBJECTFILE=uc_exe_.o
-STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
-
-ifeq ($(FIRSTLIB),)
-FIRSTLIB:=eexe.lib
-else
-ifneq ($(findstring kc_exe,$(FIRSTLIB))$(findstring KC_EXE,$(FIRSTLIB)),)
-STATIC_RUNTIME_LIB:=$(KERNEL_STATIC_RUNTIME_LIB)
-CDEFS:=$(CDEFS) __KERNEL_MODE__
-FIRSTLIB_OBJECTFILE=k_entry_.o
-# Kernel code builds as arm
-ALWAYS_BUILD_AS_ARM:=1
-# No exception support for kernel code
-EXCEPTIONS:=$(NO_EXCEPTIONS)
-# No dedicated library for operator new/delete functions.
-HAS_DEDICATED_OP_NEWDEL_LIB:=
-
-endif
-endif
-
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/$(FIRSTLIB)
-
-ifeq ("$(TOOLCHAIN)","RVCT")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Startup  $(call dblquote,$(STATIC_RUNTIME_DIR)/$(FIRSTLIB)($(FIRSTLIB_OBJECTFILE)))
-else
-# GCCE
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Startup -u _E32Startup  $(call dblquote,$(STATIC_RUNTIME_DIR)/$(FIRSTLIB))
-endif
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-
-POSTLINKDEFFILE:=$(DEFFILE)
-SUPPORT_FREEZE:=1
-ifeq ($(NOEXPORTLIBRARY),)
-IMPORTLIBRARYREQUIRED:=1
-else
-IMPORTLIBRARYREQUIRED:=
-endif
-
-
-CDEFS:=$(CDEFS) __EXE__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-
-else
-$(error $e32abiv2exexp.flm called with wrong TARGETTYPE (should be 'exexp' but is '$(TARGETTYPE)'))
-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:
+# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
+# Build an e32 EXE with exports
+# 
+#
+
+ifeq ($(TARGETTYPE),exexp)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+# What we need to build an EXEXP
+CANHAVEEXPORTS:=1
+POSTLINKTARGETTYPE:=EXEXP
+POSTLINKFILETYPE:=exe
+DOPOSTLINK:=1
+EPOCALLOWDLLDATA:=1
+CANIGNORENONCALLABLE:=1
+
+$(call vsave,CDEFS)
+# Determine what kind of entrypoint option to set
+FIRSTLIB_OBJECTFILE=uc_exe_.o
+STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
+
+ifeq ($(FIRSTLIB),)
+FIRSTLIB:=eexe.lib
+else
+ifneq ($(findstring kc_exe,$(FIRSTLIB))$(findstring KC_EXE,$(FIRSTLIB)),)
+STATIC_RUNTIME_LIB:=$(KERNEL_STATIC_RUNTIME_LIB)
+CDEFS:=$(CDEFS) __KERNEL_MODE__
+FIRSTLIB_OBJECTFILE=k_entry_.o
+# Kernel code builds as arm
+ALWAYS_BUILD_AS_ARM:=1
+# No exception support for kernel code
+EXCEPTIONS:=$(NO_EXCEPTIONS)
+# No dedicated library for operator new/delete functions.
+HAS_DEDICATED_OP_NEWDEL_LIB:=
+
+endif
+endif
+
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/$(FIRSTLIB)
+
+ifeq ("$(TOOLCHAIN)","RVCT")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Startup $(call dblquote,$(STATIC_RUNTIME_DIR)/$(FIRSTLIB)($(FIRSTLIB_OBJECTFILE)))
+else
+# GCCE
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Startup -Wl,-u$(LINKER_SEPARATOR)_E32Startup$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/$(FIRSTLIB))
+endif
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+ifeq ($(NOEXPORTLIBRARY),)
+IMPORTLIBRARYREQUIRED:=1
+else
+IMPORTLIBRARYREQUIRED:=
+endif
+
+
+CDEFS:=$(CDEFS) __EXE__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+
+else
+$(error $e32abiv2exexp.flm called with wrong TARGETTYPE (should be 'exexp' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/e32abiv2fsy.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2fsy.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,55 +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:
-# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
-# Build an e32 fsy - a filesystem driver
-# 
-#
-
-ifeq ($(TARGETTYPE),fsy)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-# What we need to build a DLL
-CANHAVEEXPORTS:=1
-POSTLINKTARGETTYPE:=FSY
-POSTLINKFILETYPE:=fsy
-DOPOSTLINK:=1
-
-# Determine what kind of entrypoint option to set
-AUTOEXPORTS:=CreateFileSystem,1;
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edll.lib
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Dll $(LINKER_ENTRYPOINT_DECORATION) $(call dblquote,$(STATIC_RUNTIME_DIR)/edll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
-
-UID2:=100039df
-STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
-CANIGNORENONCALLABLE:=1
-
-
-# We are appending to CDEFS but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS)
-CDEFS:=$(CDEFS) __DLL__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2fsy.flm called with wrong TARGETTYPE (should be 'fsy' but is '$(TARGETTYPE)'))
-endif
-
+# 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:
+# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
+# Build an e32 fsy - a filesystem driver
+# 
+#
+
+ifeq ($(TARGETTYPE),fsy)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+# What we need to build a DLL
+CANHAVEEXPORTS:=1
+POSTLINKTARGETTYPE:=FSY
+POSTLINKFILETYPE:=fsy
+DOPOSTLINK:=1
+
+# Determine what kind of entrypoint option to set
+AUTOEXPORTS:=CreateFileSystem,1;
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edll.lib
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Dll $(LINKER_ENTRYPOINT_DECORATION)$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/edll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
+
+# Fixed export TARGETTYPEs should only reference a .def file if an explicit DEFFILE statement is present in the .mmp file
+ifneq ($(DEFFILEKEYWORD),)
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+ifeq ($(NOEXPORTLIBRARY),)
+IMPORTLIBRARYREQUIRED:=1
+endif
+endif
+
+UID2:=100039df
+STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
+CANIGNORENONCALLABLE:=1
+
+
+# We are appending to CDEFS but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS)
+CDEFS:=$(CDEFS) __DLL__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error $e32abiv2fsy.flm called with wrong TARGETTYPE (should be 'fsy' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/e32abiv2implib.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2implib.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,46 +1,46 @@
-# 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:
-# ARMv5 LIB ABIv2 Function Like Makefile (FLM)
-# Build an e32 static library
-# 
-#
-
-ifeq ($(TARGETTYPE),implib)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-# What we need to build an import library
-POSTLINKFILETYPE:=dll
-# Determine what kind of entrypoint option to set
-IMPORTLIBRARYREQUIRED:=1
-POSTLINKDEFFILE:=$(DEFFILE)
-SUPPORT_FREEZE:=1
-
-# Import libraries are always built as .dso but
-# in their --linkas option they are meant to
-# "front" a dll.  So:
-REQUESTEDTARGETEXT:=dll
-# if there is a LINKAS variable then this won't matter
-
-
-# We are appending to CDEFS but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS)
-CDEFS:=$(CDEFS) __DLL__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2implib.flm called with wrong TARGETTYPE (should be 'implib' but is '$(TARGETTYPE)'))
-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:
+# ARMv5 LIB ABIv2 Function Like Makefile (FLM)
+# Build an e32 static library
+# 
+#
+
+ifeq ($(TARGETTYPE),implib)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+# What we need to build an import library
+POSTLINKFILETYPE:=dll
+# Determine what kind of entrypoint option to set
+IMPORTLIBRARYREQUIRED:=1
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+
+# Import libraries are always built as .dso but
+# in their --linkas option they are meant to
+# "front" a dll.  So:
+REQUESTEDTARGETEXT:=dll
+# if there is a LINKAS variable then this won't matter
+
+
+# We are appending to CDEFS but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS)
+CDEFS:=$(CDEFS) __DLL__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error $e32abiv2implib.flm called with wrong TARGETTYPE (should be 'implib' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/e32abiv2kdll.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2kdll.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,69 +1,70 @@
-# 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:
-# ARMv5 KDLL ABIv2 Function Like Makefile (FLM)
-# Build an e32 KDLL (Kernel DLL)
-# 
-#
-
-ifeq ($(TARGETTYPE),kdll)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-# What we need to build a Kernel DLL
-CANHAVEEXPORTS:=1
-POSTLINKTARGETTYPE:=DLL
-POSTLINKFILETYPE:=dll
-DOPOSTLINK:=1
-
-# Determine what kind of entrypoint option to set
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/ekll.lib
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Dll $(LINKER_ENTRYPOINT_DECORATION) $(call dblquote,$(STATIC_RUNTIME_DIR)/ekll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
-STATIC_RUNTIME_LIB:=$(KERNEL_STATIC_RUNTIME_LIB)
-RUNTIME_LIBS_LIST:=
-
-# Kernel code builds as arm
-ALWAYS_BUILD_AS_ARM:=1
-
-# No dedicated library for operator new/delete functions.
-HAS_DEDICATED_OP_NEWDEL_LIB:=
-
-BASELIBS:=ekll.lib
-ifeq ($(NOEXPORTLIBRARY),)
-IMPORTLIBRARYREQUIRED:=1
-endif
-POSTLINKDEFFILE:=$(DEFFILE)
-
-# No exception support for kernel code?
-EXCEPTIONS:=$(NO_EXCEPTIONS)
-
-
-
-# We are appending to CDEFS but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS SYSTEMINCLUDE)
-SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/nkern $(EPOCROOT)/epoc32/include/kernel/arm $(EPOCROOT)/epoc32/include/memmodel/epoc $(EPOCROOT)/epoc32/include/kernel  $(EPOCROOT)/epoc32/include/nkern/arm
-CDEFS:=$(CDEFS) __DLL__ __KERNEL_MODE__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2kdll.flm called with wrong TARGETTYPE (should be 'kdll' but is '$(TARGETTYPE)'))
-endif
-
+# 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:
+# ARMv5 KDLL ABIv2 Function Like Makefile (FLM)
+# Build an e32 KDLL (Kernel DLL)
+# 
+#
+
+ifeq ($(TARGETTYPE),kdll)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+# What we need to build a Kernel DLL
+CANHAVEEXPORTS:=1
+POSTLINKTARGETTYPE:=DLL
+POSTLINKFILETYPE:=dll
+DOPOSTLINK:=1
+
+# Determine what kind of entrypoint option to set
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/ekll.lib
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Dll $(LINKER_ENTRYPOINT_DECORATION)$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/ekll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
+STATIC_RUNTIME_LIB:=$(KERNEL_STATIC_RUNTIME_LIB)
+RUNTIME_LIBS_LIST:=
+
+# Kernel code builds as arm
+ALWAYS_BUILD_AS_ARM:=1
+
+# No dedicated library for operator new/delete functions.
+HAS_DEDICATED_OP_NEWDEL_LIB:=
+
+BASELIBS:=ekll.lib
+ifeq ($(NOEXPORTLIBRARY),)
+IMPORTLIBRARYREQUIRED:=1
+endif
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+
+# No exception support for kernel code?
+EXCEPTIONS:=$(NO_EXCEPTIONS)
+
+
+
+# We are appending to CDEFS but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS SYSTEMINCLUDE)
+SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/nkern $(EPOCROOT)/epoc32/include/kernel/arm $(EPOCROOT)/epoc32/include/memmodel/epoc $(EPOCROOT)/epoc32/include/kernel  $(EPOCROOT)/epoc32/include/nkern/arm
+CDEFS:=$(CDEFS) __DLL__ __KERNEL_MODE__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error $e32abiv2kdll.flm called with wrong TARGETTYPE (should be 'kdll' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/e32abiv2kext.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2kext.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,78 +1,78 @@
-# 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:
-# ARMv5 KEXT ABIv2 Function Like Makefile (FLM)
-# Build an e32 KEXT (Kernel Extension)
-# 
-#
-
-ifeq ($(TARGETTYPE),kext)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-
-# What we need to build a Kernel Extension
-# an import library isn't strictly required, apparently. So only try to
-# generate one if the def file exists.
-ifeq ($(NOEXPORTLIBRARY),)
-ifneq ($(DEFFILE),)
-IMPORTLIBRARYREQUIRED:=1
-endif
-endif
-
-POSTLINKDEFFILE:=$(DEFFILE)
-SUPPORT_FREEZE:=1
-
-# Default Linker settings for this target type
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/eext.lib
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Dll $(LINKER_ENTRYPOINT_DECORATION) $(call dblquote,$(STATIC_RUNTIME_DIR)/eext.lib$(LINKER_ENTRYPOINT_ADORNMENT))
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
-STATIC_RUNTIME_LIB:=$(KERNEL_STATIC_RUNTIME_LIB)
-RUNTIME_LIBS_LIST:=
-CANIGNORENONCALLABLE:=1
-
-# Kernel code builds as arm
-ALWAYS_BUILD_AS_ARM:=1
-CANHAVEEXPORTS:=1
-POSTLINKTARGETTYPE:=KEXT
-POSTLINKFILETYPE:=dll
-DOPOSTLINK:=1
-
-# No dedicated library for operator new/delete functions.
-HAS_DEDICATED_OP_NEWDEL_LIB:=
-
-# No exception support for kernel code?
-EXCEPTIONS:=$(NO_EXCEPTIONS)
-
-
-BASELIBS:=eext.lib
-
-
-# Use the general EABI FLM 
-# We are appending to CDEFS and SYSTEMINCLUDE but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS SYSTEMINCLUDE)
-SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/nkern $(EPOCROOT)/epoc32/include/kernel/arm $(EPOCROOT)/epoc32/include/memmodel/epoc $(EPOCROOT)/epoc32/include/kernel  $(EPOCROOT)/epoc32/include/nkern/arm
-CDEFS:=$(CDEFS) __DLL__ __KERNEL_MODE__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2kext.flm called with wrong TARGETTYPE (should be 'kext' but is '$(TARGETTYPE)'))
-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:
+# ARMv5 KEXT ABIv2 Function Like Makefile (FLM)
+# Build an e32 KEXT (Kernel Extension)
+# 
+#
+
+ifeq ($(TARGETTYPE),kext)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+
+# What we need to build a Kernel Extension
+# an import library isn't strictly required, apparently. So only try to
+# generate one if the def file exists.
+ifeq ($(NOEXPORTLIBRARY),)
+ifneq ($(DEFFILE),)
+IMPORTLIBRARYREQUIRED:=1
+endif
+endif
+
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+
+# Default Linker settings for this target type
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/eext.lib
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Dll $(LINKER_ENTRYPOINT_DECORATION)$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/eext.lib$(LINKER_ENTRYPOINT_ADORNMENT))
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
+STATIC_RUNTIME_LIB:=$(KERNEL_STATIC_RUNTIME_LIB)
+RUNTIME_LIBS_LIST:=
+CANIGNORENONCALLABLE:=1
+
+# Kernel code builds as arm
+ALWAYS_BUILD_AS_ARM:=1
+CANHAVEEXPORTS:=1
+POSTLINKTARGETTYPE:=KEXT
+POSTLINKFILETYPE:=dll
+DOPOSTLINK:=1
+
+# No dedicated library for operator new/delete functions.
+HAS_DEDICATED_OP_NEWDEL_LIB:=
+
+# No exception support for kernel code?
+EXCEPTIONS:=$(NO_EXCEPTIONS)
+
+
+BASELIBS:=eext.lib
+
+
+# Use the general EABI FLM 
+# We are appending to CDEFS and SYSTEMINCLUDE but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS SYSTEMINCLUDE)
+SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/nkern $(EPOCROOT)/epoc32/include/kernel/arm $(EPOCROOT)/epoc32/include/memmodel/epoc $(EPOCROOT)/epoc32/include/kernel  $(EPOCROOT)/epoc32/include/nkern/arm
+CDEFS:=$(CDEFS) __DLL__ __KERNEL_MODE__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error $e32abiv2kext.flm called with wrong TARGETTYPE (should be 'kext' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/e32abiv2klib.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2klib.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,41 +1,41 @@
-# 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:
-# ARMv5 LIB ABIv2 Function Like Makefile (FLM)
-# Build an e32 static library for kernel code
-# 
-#
-
-ifeq ($(TARGETTYPE),klib)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-# What we need to build a kernel LIB
-POSTLINKFILETYPE:=lib
-
-# Kernel code builds as arm
-ALWAYS_BUILD_AS_ARM:=1
-
-# No exception support for kernel code?
-EXCEPTIONS:=$(NO_EXCEPTIONS)
-
-# We are appending to CDEFS but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS)
-CDEFS:=$(CDEFS) __KERNEL_MODE__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2klib.flm called with wrong TARGETTYPE (should be 'klib' but is '$(TARGETTYPE)'))
-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:
+# ARMv5 LIB ABIv2 Function Like Makefile (FLM)
+# Build an e32 static library for kernel code
+# 
+#
+
+ifeq ($(TARGETTYPE),klib)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+# What we need to build a kernel LIB
+POSTLINKFILETYPE:=lib
+
+# Kernel code builds as arm
+ALWAYS_BUILD_AS_ARM:=1
+
+# No exception support for kernel code?
+EXCEPTIONS:=$(NO_EXCEPTIONS)
+
+# We are appending to CDEFS but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS)
+CDEFS:=$(CDEFS) __KERNEL_MODE__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error $e32abiv2klib.flm called with wrong TARGETTYPE (should be 'klib' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/e32abiv2ldd.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2ldd.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,80 +1,89 @@
-# 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:
-# ARMv5 ldd ABIv2 Function Like Makefile (FLM)
-# Build an e32 ldd (Logical Device Driver)
-# 
-#
-
-ifeq ($(TARGETTYPE),ldd)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-
-# What we need to build a Logical Device Driver
-CANHAVEEXPORTS:=1
-POSTLINKTARGETTYPE:=LDD
-POSTLINKFILETYPE:=ldd
-DOPOSTLINK:=1
-AUTOEXPORTS:=_Z19CreateLogicalDevicev,1;
-
-# Determine what kind of entrypoint option to set
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edev.lib
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Dll $(LINKER_ENTRYPOINT_DECORATION) $(call dblquote,$(STATIC_RUNTIME_DIR)/edev.lib$(LINKER_ENTRYPOINT_ADORNMENT))
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
-STATIC_RUNTIME_LIB:=$(KERNEL_STATIC_RUNTIME_LIB)
-RUNTIME_LIBS_LIST:=
-CANIGNORENONCALLABLE:=1
-
-# Kernel code builds as arm
-ALWAYS_BUILD_AS_ARM:=1
-
-# No dedicated library for operator new/delete functions.
-HAS_DEDICATED_OP_NEWDEL_LIB:=
-
-BASELIBS:=edev
-UID2:=100000af
-
-# No exception support for kernel code?
-EXCEPTIONS:=$(NO_EXCEPTIONS)
-
-# Only process a def file if it's specified
-# in the MMP - not if it's merely the frontend's guess
-# at what the def file name might be
-IMPORTLIBRARYREQUIRED:=
-
-ifeq ($(NOEXPORTLIBRARY),)
-ifneq ($(DEFFILE),)
-IMPORTLIBRARYREQUIRED:=1
-endif
-endif
-POSTLINKDEFFILE:=$(DEFFILE)
-SUPPORT_FREEZE:=1
-
-# We are appending to CDEFS but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS SYSTEMINCLUDE)
-SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/nkern $(EPOCROOT)/epoc32/include/kernel/arm $(EPOCROOT)/epoc32/include/memmodel/epoc $(EPOCROOT)/epoc32/include/kernel  $(EPOCROOT)/epoc32/include/nkern/arm
-CDEFS:=$(CDEFS) __DLL__ __KERNEL_MODE__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2ldd.flm called with wrong TARGETTYPE (should be 'ldd' but is '$(TARGETTYPE)'))
-endif
-
+# 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:
+# ARMv5 ldd ABIv2 Function Like Makefile (FLM)
+# Build an e32 ldd (Logical Device Driver)
+# 
+#
+
+ifeq ($(TARGETTYPE),ldd)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+
+# What we need to build a Logical Device Driver
+CANHAVEEXPORTS:=1
+POSTLINKTARGETTYPE:=LDD
+POSTLINKFILETYPE:=ldd
+DOPOSTLINK:=1
+AUTOEXPORTS:=_Z19CreateLogicalDevicev,1;
+
+# Determine what kind of entrypoint option to set
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edev.lib
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Dll $(LINKER_ENTRYPOINT_DECORATION)$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/edev.lib$(LINKER_ENTRYPOINT_ADORNMENT))
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
+STATIC_RUNTIME_LIB:=$(KERNEL_STATIC_RUNTIME_LIB)
+RUNTIME_LIBS_LIST:=
+CANIGNORENONCALLABLE:=1
+
+# Kernel code builds as arm
+ALWAYS_BUILD_AS_ARM:=1
+
+# No dedicated library for operator new/delete functions.
+HAS_DEDICATED_OP_NEWDEL_LIB:=
+
+# Fixed export TARGETTYPEs should only reference a .def file if an explicit DEFFILE statement is present in the .mmp file
+ifneq ($(DEFFILEKEYWORD),)
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+ifeq ($(NOEXPORTLIBRARY),)
+IMPORTLIBRARYREQUIRED:=1
+endif
+endif
+
+BASELIBS:=edev
+UID2:=100000af
+
+# No exception support for kernel code?
+EXCEPTIONS:=$(NO_EXCEPTIONS)
+
+# Only process a def file if it's specified
+# in the MMP - not if it's merely the frontend's guess
+# at what the def file name might be
+IMPORTLIBRARYREQUIRED:=
+
+ifeq ($(NOEXPORTLIBRARY),)
+ifneq ($(DEFFILE),)
+IMPORTLIBRARYREQUIRED:=1
+endif
+endif
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+
+# We are appending to CDEFS but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS SYSTEMINCLUDE)
+SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/nkern $(EPOCROOT)/epoc32/include/kernel/arm $(EPOCROOT)/epoc32/include/memmodel/epoc $(EPOCROOT)/epoc32/include/kernel  $(EPOCROOT)/epoc32/include/nkern/arm
+CDEFS:=$(CDEFS) __DLL__ __KERNEL_MODE__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error $e32abiv2ldd.flm called with wrong TARGETTYPE (should be 'ldd' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/e32abiv2lib.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2lib.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,32 +1,32 @@
-# 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:
-# ARMv5 LIB ABIv2 Function Like Makefile (FLM)
-# Build an e32 static library
-# 
-#
-
-ifeq ($(TARGETTYPE),lib)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-ifeq ($(FEATUREVARIANT),1)
-$(error TARGETTYPE lib cannot be FEATUREVARIANT (in $(PROJECT_META) from $(COMPONENT_META)))
-endif
-
-POSTLINKFILETYPE:=lib
-MULTIFILE_ENABLED:=
-include $(FLMHOME)/e32abiv2.flm
-
-else
-$(error $e32abiv2dll.flm called with wrong TARGETTYPE (should be 'lib' but is '$(TARGETTYPE)'))
-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:
+# ARMv5 LIB ABIv2 Function Like Makefile (FLM)
+# Build an e32 static library
+# 
+#
+
+ifeq ($(TARGETTYPE),lib)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+ifeq ($(FEATUREVARIANT),1)
+$(error TARGETTYPE lib cannot be FEATUREVARIANT (in $(PROJECT_META) from $(COMPONENT_META)))
+endif
+
+POSTLINKFILETYPE:=lib
+MULTIFILE_ENABLED:=
+include $(FLMHOME)/e32abiv2.flm
+
+else
+$(error $e32abiv2dll.flm called with wrong TARGETTYPE (should be 'lib' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/e32abiv2none.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2none.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,36 +1,36 @@
-# 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:
-# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
-# Build Resources only
-# 
-#
-
-ifeq ($(TARGETTYPE),none)
-include $(FLMHOME)/e32abiv2defaults.mk
-POSTLINKTARGETTYPE:=NONE
-POSTLINKFILETYPE:=none
-
-
-# We are appending to CDEFS but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS)
-CDEFS:=$(CDEFS) __DLL__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2none.flm called with wrong TARGETTYPE (should be 'none' but is '$(TARGETTYPE)'))
-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:
+# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
+# Build Resources only
+# 
+#
+
+ifeq ($(TARGETTYPE),none)
+include $(FLMHOME)/e32abiv2defaults.mk
+POSTLINKTARGETTYPE:=NONE
+POSTLINKFILETYPE:=none
+
+
+# We are appending to CDEFS but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS)
+CDEFS:=$(CDEFS) __DLL__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error $e32abiv2none.flm called with wrong TARGETTYPE (should be 'none' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/e32abiv2pdd.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2pdd.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,77 +1,85 @@
-# 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:
-# ARMv5 pdd ABIv2 Function Like Makefile (FLM)
-# Build an e32 pdd (Physical Device Driver)
-# 
-#
-
-ifeq ($(TARGETTYPE),pdd)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-# What we need to build a Logical Device Driver
-CANHAVEEXPORTS:=1
-POSTLINKTARGETTYPE:=PDD
-POSTLINKFILETYPE:=pdd
-DOPOSTLINK:=1
-AUTOEXPORTS:=_Z20CreatePhysicalDevicev,1;
-
-# Determine what kind of entrypoint option to set
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edev.lib
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Dll $(LINKER_ENTRYPOINT_DECORATION) $(call dblquote,$(STATIC_RUNTIME_DIR)/edev.lib$(LINKER_ENTRYPOINT_ADORNMENT))
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
-STATIC_RUNTIME_LIB:=$(KERNEL_STATIC_RUNTIME_LIB)
-RUNTIME_LIBS_LIST:=
-CANIGNORENONCALLABLE:=1
-
-# Kernel code builds as arm
-ALWAYS_BUILD_AS_ARM:=1
-
-# No dedicated library for operator new/delete functions.
-HAS_DEDICATED_OP_NEWDEL_LIB:=
-
-
-BASELIBS:=edev
-UID2:=100039d0
-
-IMPORTLIBRARYREQUIRED:=
-# This is basically a DLL with some tweaks
-ifneq ($(DEFFILE),)
-IMPORTLIBRARYREQUIRED:=1
-endif
-POSTLINKDEFFILE:=$(DEFFILE)
-SUPPORT_FREEZE:=1
-
-# No exception support for kernel code?
-EXCEPTIONS:=$(NO_EXCEPTIONS)
-
-
-
-# We are appending to CDEFS but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS SYSTEMINCLUDE)
-SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/nkern $(EPOCROOT)/epoc32/include/kernel/arm $(EPOCROOT)/epoc32/include/memmodel/epoc $(EPOCROOT)/epoc32/include/kernel  $(EPOCROOT)/epoc32/include/nkern/arm
-CDEFS:=$(CDEFS) __DLL__ __KERNEL_MODE__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2pdd.flm called with wrong TARGETTYPE (should be 'pdd' but is '$(TARGETTYPE)'))
-endif
-
+# 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:
+# ARMv5 pdd ABIv2 Function Like Makefile (FLM)
+# Build an e32 pdd (Physical Device Driver)
+# 
+#
+
+ifeq ($(TARGETTYPE),pdd)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+# What we need to build a Logical Device Driver
+CANHAVEEXPORTS:=1
+POSTLINKTARGETTYPE:=PDD
+POSTLINKFILETYPE:=pdd
+DOPOSTLINK:=1
+AUTOEXPORTS:=_Z20CreatePhysicalDevicev,1;
+
+# Determine what kind of entrypoint option to set
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edev.lib
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Dll $(LINKER_ENTRYPOINT_DECORATION)$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/edev.lib$(LINKER_ENTRYPOINT_ADORNMENT))
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
+STATIC_RUNTIME_LIB:=$(KERNEL_STATIC_RUNTIME_LIB)
+RUNTIME_LIBS_LIST:=
+CANIGNORENONCALLABLE:=1
+
+# Kernel code builds as arm
+ALWAYS_BUILD_AS_ARM:=1
+
+# No dedicated library for operator new/delete functions.
+HAS_DEDICATED_OP_NEWDEL_LIB:=
+
+# Fixed export TARGETTYPEs should only reference a .def file if an explicit DEFFILE statement is present in the .mmp file
+ifneq ($(DEFFILEKEYWORD),)
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+ifeq ($(NOEXPORTLIBRARY),)
+IMPORTLIBRARYREQUIRED:=1
+endif
+endif
+
+BASELIBS:=edev
+UID2:=100039d0
+
+IMPORTLIBRARYREQUIRED:=
+# This is basically a DLL with some tweaks
+ifneq ($(DEFFILE),)
+IMPORTLIBRARYREQUIRED:=1
+endif
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+
+# No exception support for kernel code?
+EXCEPTIONS:=$(NO_EXCEPTIONS)
+
+
+
+# We are appending to CDEFS but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS SYSTEMINCLUDE)
+SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/nkern $(EPOCROOT)/epoc32/include/kernel/arm $(EPOCROOT)/epoc32/include/memmodel/epoc $(EPOCROOT)/epoc32/include/kernel  $(EPOCROOT)/epoc32/include/nkern/arm
+CDEFS:=$(CDEFS) __DLL__ __KERNEL_MODE__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error $e32abiv2pdd.flm called with wrong TARGETTYPE (should be 'pdd' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/e32abiv2pdl.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2pdl.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,56 +1,65 @@
-# 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:
-# ARMv5 pdl ABIv2 Function Like Makefile (FLM)
-# Build an e32 pdl (Printer Device)
-# 
-#
-
-ifeq ($(TARGETTYPE),pdl)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-# What we need to build a Printer Device
-CANHAVEEXPORTS:=1
-POSTLINKTARGETTYPE:=PDL
-POSTLINKFILETYPE:=pdl
-DOPOSTLINK:=1
-AUTOEXPORTS:=_Z17NewPrinterDeviceLv,1;
-
-# Determine what kind of entrypoint option to set
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edll.lib
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Dll $(LINKER_ENTRYPOINT_DECORATION) $(call dblquote,$(STATIC_RUNTIME_DIR)/edll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
-STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
-CANIGNORENONCALLABLE:=1
-
-BASELIBS:=
-UID2:=10003b1c
-RESOURCEPATH:=Resource\Printers
-
-# We are appending to CDEFS but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS)
-CDEFS:=$(CDEFS) __DLL__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2pdl.flm called with wrong TARGETTYPE (should be 'pdl' but is '$(TARGETTYPE)'))
-endif
-
+# 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:
+# ARMv5 pdl ABIv2 Function Like Makefile (FLM)
+# Build an e32 pdl (Printer Device)
+# 
+#
+
+ifeq ($(TARGETTYPE),pdl)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+# What we need to build a Printer Device
+CANHAVEEXPORTS:=1
+POSTLINKTARGETTYPE:=PDL
+POSTLINKFILETYPE:=pdl
+DOPOSTLINK:=1
+AUTOEXPORTS:=_Z17NewPrinterDeviceLv,1;
+
+# Determine what kind of entrypoint option to set
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edll.lib
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Dll $(LINKER_ENTRYPOINT_DECORATION)$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/edll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
+STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
+CANIGNORENONCALLABLE:=1
+
+# Fixed export TARGETTYPEs should only reference a .def file if an explicit DEFFILE statement is present in the .mmp file
+ifneq ($(DEFFILEKEYWORD),)
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+ifeq ($(NOEXPORTLIBRARY),)
+IMPORTLIBRARYREQUIRED:=1
+endif
+endif
+
+BASELIBS:=
+UID2:=10003b1c
+RESOURCEPATH:=Resource\Printers
+
+# We are appending to CDEFS but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS)
+CDEFS:=$(CDEFS) __DLL__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error $e32abiv2pdl.flm called with wrong TARGETTYPE (should be 'pdl' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/e32abiv2plugin.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2plugin.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,69 +1,72 @@
-# 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:
-# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
-# Build an ECOM plugin
-# 
-#
-
-ifeq ($(TARGETTYPE),plugin)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-# This is basically a DLL with some tweaks
-# If DEFFILE keyword is specified in the MMP, set the POSTLINKDEFFILE
-# and guarantee the generation of import library; if not specified import library
-# won't be generated for plugin (default)
-ifneq ($(DEFFILEKEYWORD),)
-POSTLINKDEFFILE:=$(DEFFILE)
-SUPPORT_FREEZE:=1
-IMPORTLIBRARYREQUIRED:=1
-endif
-
-# Default Linker settings for this target type
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edll.lib
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Dll $(LINKER_ENTRYPOINT_DECORATION) $(call dblquote,$(STATIC_RUNTIME_DIR)/edll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
-STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
-
-# Default Postlinker settings
-CANHAVEEXPORTS:=1
-POSTLINKTARGETTYPE:=PLUGIN
-POSTLINKFILETYPE:=dll
-DOPOSTLINK:=1
-AUTOEXPORTS:=_Z24ImplementationGroupProxyRi,1;
-CANIGNORENONCALLABLE:=1
-
-# We could check the UID rather than forcing it
-# but there seems to be no point in that.
-UID2:=10009D8D
-
-
-RESOURCEPATH:=Resource/Plugins
-
-# Use the general EABI FLM 
-# We are appending to CDEFS but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS)
-CDEFS:=$(CDEFS) __DLL__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2plugin.flm called with wrong TARGETTYPE (should be 'plugin' but is '$(TARGETTYPE)'))
-endif
+# 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:
+# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
+# Build an ECOM plugin
+# 
+#
+
+ifneq ($(filter plugin plugin3,$(TARGETTYPE)),)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+# Default Linker settings for this target type
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edll.lib
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Dll $(LINKER_ENTRYPOINT_DECORATION)$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/edll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
+STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
+
+# Default Postlinker settings
+CANHAVEEXPORTS:=1
+POSTLINKTARGETTYPE:=PLUGIN
+POSTLINKFILETYPE:=dll
+DOPOSTLINK:=1
+AUTOEXPORTS:=_Z24ImplementationGroupProxyRi,1;
+CANIGNORENONCALLABLE:=1
+
+# Fixed export TARGETTYPEs should only reference a .def file if an explicit DEFFILE statement is present in the .mmp file
+ifneq ($(DEFFILEKEYWORD),)
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+ifeq ($(NOEXPORTLIBRARY),)
+IMPORTLIBRARYREQUIRED:=1
+endif
+endif
+
+# We could check the UID rather than forcing it
+# but there seems to be no point in that.
+UID2:=10009D8D
+ifeq ($(TARGETTYPE),plugin3)
+UID2:=10009D93
+POSTLINKTARGETTYPE:=PLUGIN3
+endif
+
+
+RESOURCEPATH:=Resource/Plugins
+
+# Use the general EABI FLM 
+# We are appending to CDEFS but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS)
+CDEFS:=$(CDEFS) __DLL__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error $e32abiv2plugin.flm called with wrong TARGETTYPE (should be 'plugin' or 'plugin3' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/e32abiv2stddll.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2stddll.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,69 +1,69 @@
-# 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:
-# e32abiv2dll.flm
-# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
-# Build an e32 DLL (Dynamic Link Library)
-# 
-#
-
-ifeq ($(TARGETTYPE),stddll)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-# What we need to build a DLL
-ifeq ($(NOEXPORTLIBRARY),)
-IMPORTLIBRARYREQUIRED:=1
-endif
-POSTLINKDEFFILE:=$(DEFFILE)
-SUPPORT_FREEZE:=1
-
-# Default Linker settings for this target type
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edll.lib
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Dll $(LINKER_ENTRYPOINT_DECORATION) $(call dblquote,$(STATIC_RUNTIME_DIR)/edll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
-DEFAULT_NEWLIB:=$(DEFAULT_STDCPP_NEWLIB)
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
-STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
-LIBRARY:=$(LIBRARY) euser.dso
-
-
-# Default Postlinker settings
-CANHAVEEXPORTS:=1
-POSTLINKTARGETTYPE:=STDDLL
-POSTLINKFILETYPE:=dll
-DOPOSTLINK:=1
-CANIGNORENONCALLABLE:=1
-NAMEDSYMLKUP:=1
-
-# Use the general EABI FLM 
-# We are appending to CDEFS but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS SYSTEMINCLUDE)
-
-#compile options
-SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/stdapis
-NOHIDEALL:=1
-CDEFS:=$(CDEFS) __DLL__
-
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error e32abiv2stddll.flm called with wrong TARGETTYPE (should be 'stddll' but is '$(TARGETTYPE)'))
-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:
+# e32abiv2dll.flm
+# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
+# Build an e32 DLL (Dynamic Link Library)
+# 
+#
+
+ifeq ($(TARGETTYPE),stddll)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+# What we need to build a DLL
+ifeq ($(NOEXPORTLIBRARY),)
+IMPORTLIBRARYREQUIRED:=1
+endif
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+
+# Default Linker settings for this target type
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edll.lib
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Dll $(LINKER_ENTRYPOINT_DECORATION)$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/edll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
+DEFAULT_NEWLIB:=$(DEFAULT_STDCPP_NEWLIB)
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
+STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
+LIBRARY:=$(LIBRARY) euser.dso
+
+
+# Default Postlinker settings
+CANHAVEEXPORTS:=1
+POSTLINKTARGETTYPE:=STDDLL
+POSTLINKFILETYPE:=dll
+DOPOSTLINK:=1
+CANIGNORENONCALLABLE:=1
+NAMEDSYMLKUP:=1
+
+# Use the general EABI FLM 
+# We are appending to CDEFS but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS SYSTEMINCLUDE)
+
+#compile options
+SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/stdapis
+NOHIDEALL:=1
+CDEFS:=$(CDEFS) __DLL__
+
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error e32abiv2stddll.flm called with wrong TARGETTYPE (should be 'stddll' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/e32abiv2stdexe.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2stdexe.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,63 +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:
-# e32abiv2exe.flm
-# ARMv5 STDEXE/DLL ABIv2 Function Like Makefile (FLM)
-# Build an e32 STDEXE
-# 
-#
-
-# What we need to build a STDEXE
-
-ifeq ($(TARGETTYPE),stdexe)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-POSTLINKTARGETTYPE:=STDEXE
-POSTLINKFILETYPE:=exe
-DOPOSTLINK:=1
-# Determine what kind of entrypoint option to set
-LINKER_STUB_LIBRARY:=
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/eexe.lib
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Startup $(LINKER_ENTRYPOINT_DECORATION) $(call dblquote,$(STATIC_RUNTIME_DIR)/eexe.lib$(LINKER_ENTRYPOINT_ADORNMENT))
-DEFAULT_NEWLIB:=$(DEFAULT_STDCPP_NEWLIB)
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
-NAMEDSYMLKUP:=1
-LIBRARY:=$(LIBRARY) euser.dso
-
-MAKEDEFFILE:=
-
-$(call vsave,CDEFS SYSTEMINCLUDE STATICLIBRARY)
-
-# STDEXEs need the c runtime library
-ifneq ($(WCHARENTRYPOINT),)
-STATICLIBRARY:=$(STATICLIBRARY) libwcrt0
-else
-STATICLIBRARY:=$(STATICLIBRARY) libcrt0
-endif
-
-SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/stdapis
-CDEFS:=$(CDEFS) __EXE__
-NOHIDEALL:=1
-
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error e32abiv2stdexe.flm called with wrong TARGETTYPE (should be 'stdexe' but is '$(TARGETTYPE)'))
-endif
-
+# 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:
+# e32abiv2exe.flm
+# ARMv5 STDEXE/DLL ABIv2 Function Like Makefile (FLM)
+# Build an e32 STDEXE
+# 
+#
+
+# What we need to build a STDEXE
+
+ifeq ($(TARGETTYPE),stdexe)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+POSTLINKTARGETTYPE:=STDEXE
+POSTLINKFILETYPE:=exe
+DOPOSTLINK:=1
+# Determine what kind of entrypoint option to set
+LINKER_STUB_LIBRARY:=
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/eexe.lib
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Startup $(LINKER_ENTRYPOINT_DECORATION)$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/eexe.lib$(LINKER_ENTRYPOINT_ADORNMENT))
+DEFAULT_NEWLIB:=$(DEFAULT_STDCPP_NEWLIB)
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+ifeq ($(EPOCNESTEDEXCEPTIONS),)
+  STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
+else
+  STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB_NESTED_EXCEPTIONS)
+endif
+
+NAMEDSYMLKUP:=1
+LIBRARY:=$(LIBRARY) euser.dso
+
+$(call vsave,CDEFS SYSTEMINCLUDE STATICLIBRARY)
+
+# STDEXEs need the c runtime library
+ifneq ($(WCHARENTRYPOINT),)
+STATICLIBRARY:=$(STATICLIBRARY) libwcrt0
+else
+STATICLIBRARY:=$(STATICLIBRARY) libcrt0
+endif
+
+SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/stdapis
+CDEFS:=$(CDEFS) __EXE__
+NOHIDEALL:=1
+
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error e32abiv2stdexe.flm called with wrong TARGETTYPE (should be 'stdexe' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/e32abiv2stdlib.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2stdlib.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,32 +1,32 @@
-# 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:
-# e32abiv2lib.flm
-# ARMv5 LIB ABIv2 Function Like Makefile (FLM)
-# Build an e32 static library
-# 
-#
-
-ifeq ($(TARGETTYPE),stdlib)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-# What we need to build a LIB 
-POSTLINKFILETYPE:=lib
-
-NOHIDEALL:=1
-
-include $(FLMHOME)/e32abiv2.flm
-
-else
-$(error e32abiv2stdlib.flm called with wrong TARGETTYPE (should be 'stdlib' but is '$(TARGETTYPE)'))
-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:
+# e32abiv2lib.flm
+# ARMv5 LIB ABIv2 Function Like Makefile (FLM)
+# Build an e32 static library
+# 
+#
+
+ifeq ($(TARGETTYPE),stdlib)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+# What we need to build a LIB 
+POSTLINKFILETYPE:=lib
+
+NOHIDEALL:=1
+
+include $(FLMHOME)/e32abiv2.flm
+
+else
+$(error e32abiv2stdlib.flm called with wrong TARGETTYPE (should be 'stdlib' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/e32abiv2textnotifier2.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2textnotifier2.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,57 +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:
-# e32abiv2textnotifier.flm
-# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
-# Build an e32 textnotifier DLL
-# 
-#
-
-ifeq ($(TARGETTYPE),textnotifier2)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-# What we need to build a DLL
-CANHAVEEXPORTS:=1
-POSTLINKTARGETTYPE:=TEXTNOTIFIER2
-POSTLINKFILETYPE:=dll
-DOPOSTLINK:=1
-AUTOEXPORTS:=_Z13NotifierArrayv,1;
-# Determine what kind of entrypoint option to set
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edll.lib
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Dll $(LINKER_ENTRYPOINT_DECORATION) $(call dblquote,$(STATIC_RUNTIME_DIR)/edll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
-STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
-CANIGNORENONCALLABLE:=1
-
-RESOURCEPATH:=System/Notifiers
-UID2:=101fe38b
-POSTLINKDEFFILE:=$(DEFFILE)
-SUPPORT_FREEZE:=1
-
-# We are appending to CDEFS but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS)
-CDEFS:=$(CDEFS) __DLL__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2textnotifier.flm called with wrong TARGETTYPE (should be 'textnotifier2' but is '$(TARGETTYPE)'))
-endif
-
+# 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:
+# e32abiv2textnotifier.flm
+# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
+# Build an e32 textnotifier DLL
+# 
+#
+
+ifeq ($(TARGETTYPE),textnotifier2)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+# What we need to build a DLL
+CANHAVEEXPORTS:=1
+POSTLINKTARGETTYPE:=TEXTNOTIFIER2
+POSTLINKFILETYPE:=dll
+DOPOSTLINK:=1
+AUTOEXPORTS:=_Z13NotifierArrayv,1;
+# Determine what kind of entrypoint option to set
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/edll.lib
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Dll $(LINKER_ENTRYPOINT_DECORATION)$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/edll.lib$(LINKER_ENTRYPOINT_ADORNMENT))
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
+STATIC_RUNTIME_LIB:=$(USER_STATIC_RUNTIME_LIB)
+CANIGNORENONCALLABLE:=1
+
+# Fixed export TARGETTYPEs should only reference a .def file if an explicit DEFFILE statement is present in the .mmp file
+ifneq ($(DEFFILEKEYWORD),)
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+ifeq ($(NOEXPORTLIBRARY),)
+IMPORTLIBRARYREQUIRED:=1
+endif
+endif
+
+RESOURCEPATH:=System/Notifiers
+UID2:=101fe38b
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+
+# We are appending to CDEFS but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS)
+CDEFS:=$(CDEFS) __DLL__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error $e32abiv2textnotifier.flm called with wrong TARGETTYPE (should be 'textnotifier2' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/e32abiv2var.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2var.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,72 +1,71 @@
-# 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:
-# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
-# Build an e32 Variant DLL
-# 
-#
-
-ifeq ($(TARGETTYPE),var)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-# What we need to build a DLL
-# May need a dso e.g. ecust.dll
-ifeq ($(NOEXPORTLIBRARY),)
-IMPORTLIBRARYREQUIRED:=1
-endif
-POSTLINKDEFFILE:=$(DEFFILE)
-SUPPORT_FREEZE:=1
-
-# Determine what kind of entrypoint option to set
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/evar.lib
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Dll $(LINKER_ENTRYPOINT_DECORATION) $(call dblquote,$(STATIC_RUNTIME_DIR)/evar.lib$(LINKER_ENTRYPOINT_ADORNMENT))
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
-STATIC_RUNTIME_LIB:=$(KERNEL_STATIC_RUNTIME_LIB)
-RUNTIME_LIBS_LIST:=
-
-# Kernel code builds as arm
-ALWAYS_BUILD_AS_ARM:=1
-
-# No dedicated library for operator new/delete functions.
-HAS_DEDICATED_OP_NEWDEL_LIB:=
-
-# Default Postlinker settings
-CANHAVEEXPORTS:=1
-POSTLINKTARGETTYPE:=VAR
-POSTLINKFILETYPE:=dll
-DOPOSTLINK:=1
-AUTOEXPORTS:=_Z17VariantInitialisev,1;
-
-# No exception support for kernel code?
-EXCEPTIONS:=$(NO_EXCEPTIONS)
-
-
-
-# We are appending to CDEFS but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS SYSTEMINCLUDE)
-SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/nkern $(EPOCROOT)/epoc32/include/kernel/arm $(EPOCROOT)/epoc32/include/memmodel/epoc $(EPOCROOT)/epoc32/include/kernel $(EPOCROOT)/epoc32/include/nkern/arm
-CDEFS:=$(CDEFS) __DLL__ __KERNEL_MODE__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2var.flm called with wrong TARGETTYPE (should be 'var' but is '$(TARGETTYPE)'))
-endif
-
+# 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:
+# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
+# Build an e32 Variant DLL
+# 
+#
+
+ifeq ($(TARGETTYPE),var)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+# Determine what kind of entrypoint option to set
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/evar.lib
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Dll $(LINKER_ENTRYPOINT_DECORATION)$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/evar.lib$(LINKER_ENTRYPOINT_ADORNMENT))
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
+STATIC_RUNTIME_LIB:=$(KERNEL_STATIC_RUNTIME_LIB)
+RUNTIME_LIBS_LIST:=
+
+# Kernel code builds as arm
+ALWAYS_BUILD_AS_ARM:=1
+
+# No dedicated library for operator new/delete functions.
+HAS_DEDICATED_OP_NEWDEL_LIB:=
+
+# Default Postlinker settings
+CANHAVEEXPORTS:=1
+POSTLINKTARGETTYPE:=VAR
+POSTLINKFILETYPE:=dll
+DOPOSTLINK:=1
+AUTOEXPORTS:=_Z17VariantInitialisev,1;
+
+# No exception support for kernel code?
+EXCEPTIONS:=$(NO_EXCEPTIONS)
+
+# Fixed export TARGETTYPEs should only reference a .def file if an explicit DEFFILE statement is present in the .mmp file
+ifneq ($(DEFFILEKEYWORD),)
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+ifeq ($(NOEXPORTLIBRARY),)
+IMPORTLIBRARYREQUIRED:=1
+endif
+endif
+
+# We are appending to CDEFS but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS SYSTEMINCLUDE)
+SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/nkern $(EPOCROOT)/epoc32/include/kernel/arm $(EPOCROOT)/epoc32/include/memmodel/epoc $(EPOCROOT)/epoc32/include/kernel $(EPOCROOT)/epoc32/include/nkern/arm
+CDEFS:=$(CDEFS) __DLL__ __KERNEL_MODE__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error $e32abiv2var.flm called with wrong TARGETTYPE (should be 'var' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/e32abiv2var2.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/e32abiv2var2.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,72 +1,71 @@
-# 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:
-# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
-# Build an e32 Variant DLL (version 2)
-# 
-#
-
-ifeq ($(TARGETTYPE),var2)
-include $(FLMHOME)/e32abiv2defaults.mk
-
-# What we need to build a DLL
-# May need a dso e.g. ecust.dll
-ifeq ($(NOEXPORTLIBRARY),)
-IMPORTLIBRARYREQUIRED:=1
-endif
-POSTLINKDEFFILE:=$(DEFFILE)
-SUPPORT_FREEZE:=1
-
-# Determine what kind of entrypoint option to set
-LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/evar.lib
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION) _E32Dll $(LINKER_ENTRYPOINT_DECORATION) $(call dblquote,$(STATIC_RUNTIME_DIR)/evar.lib$(LINKER_ENTRYPOINT_ADORNMENT))
-
-ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
-LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
-endif
-
-LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
-STATIC_RUNTIME_LIB:=$(KERNEL_STATIC_RUNTIME_LIB)
-RUNTIME_LIBS_LIST:=
-
-# Kernel code builds as arm
-ALWAYS_BUILD_AS_ARM:=1
-
-# No dedicated library for operator new/delete functions.
-HAS_DEDICATED_OP_NEWDEL_LIB:=
-
-# Default Postlinker settings
-CANHAVEEXPORTS:=1
-POSTLINKTARGETTYPE:=VAR2
-POSTLINKFILETYPE:=dll
-DOPOSTLINK:=1
-AUTOEXPORTS:=VariantInitialise,1;
-
-# No exception support for kernel code?
-EXCEPTIONS:=$(NO_EXCEPTIONS)
-
-
-
-# We are appending to CDEFS but we don't want this to affect
-# other invocations so we are going to save it on a stack
-# and restore it afterwards
-$(call vsave,CDEFS SYSTEMINCLUDE)
-SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/nkern $(EPOCROOT)/epoc32/include/kernel/arm $(EPOCROOT)/epoc32/include/memmodel/epoc $(EPOCROOT)/epoc32/include/kernel $(EPOCROOT)/epoc32/include/nkern/arm
-CDEFS:=$(CDEFS) __DLL__ __KERNEL_MODE__
-include $(FLMHOME)/e32abiv2.flm
-$(call vrestore)
-
-else
-$(error $e32abiv2var2.flm called with wrong TARGETTYPE (should be 'var2' but is '$(TARGETTYPE)'))
-endif
-
+# Copyright (c) 2008-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:
+# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
+# Build an e32 Variant DLL (version 2)
+# 
+#
+
+ifeq ($(TARGETTYPE),var2)
+include $(FLMHOME)/e32abiv2defaults.mk
+
+# Determine what kind of entrypoint option to set
+LINKER_ENTRYPOINT_LIBDEP:=$(STATIC_RUNTIME_DIR)/evar.lib
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRY_OPTION)=_E32Dll $(LINKER_ENTRYPOINT_DECORATION)$(LINKER_SEPARATOR)$(call dblquote,$(STATIC_RUNTIME_DIR)/evar.lib$(LINKER_ENTRYPOINT_ADORNMENT))
+
+ifeq ("$(NEED_ENTRYPOINT_LIBRARY)","True")
+LINKER_ENTRYPOINT_SETTING:=$(LINKER_ENTRYPOINT_SETTING) $(LINKER_ENTRYPOINT_LIBDEP)
+endif
+
+LINKER_STUB_LIBRARY:=$(STATIC_RUNTIME_DIR)/edllstub.lib
+STATIC_RUNTIME_LIB:=$(KERNEL_STATIC_RUNTIME_LIB)
+RUNTIME_LIBS_LIST:=
+
+# Kernel code builds as arm
+ALWAYS_BUILD_AS_ARM:=1
+
+# No dedicated library for operator new/delete functions.
+HAS_DEDICATED_OP_NEWDEL_LIB:=
+
+# Default Postlinker settings
+CANHAVEEXPORTS:=1
+POSTLINKTARGETTYPE:=VAR2
+POSTLINKFILETYPE:=dll
+DOPOSTLINK:=1
+AUTOEXPORTS:=VariantInitialise,1;
+
+# No exception support for kernel code?
+EXCEPTIONS:=$(NO_EXCEPTIONS)
+
+# Fixed export TARGETTYPEs should only reference a .def file if an explicit DEFFILE statement is present in the .mmp file
+ifneq ($(DEFFILEKEYWORD),)
+POSTLINKDEFFILE:=$(DEFFILE)
+SUPPORT_FREEZE:=1
+ifeq ($(NOEXPORTLIBRARY),)
+IMPORTLIBRARYREQUIRED:=1
+endif
+endif
+
+# We are appending to CDEFS but we don't want this to affect
+# other invocations so we are going to save it on a stack
+# and restore it afterwards
+$(call vsave,CDEFS SYSTEMINCLUDE)
+SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(EPOCROOT)/epoc32/include/nkern $(EPOCROOT)/epoc32/include/kernel/arm $(EPOCROOT)/epoc32/include/memmodel/epoc $(EPOCROOT)/epoc32/include/kernel $(EPOCROOT)/epoc32/include/nkern/arm
+CDEFS:=$(CDEFS) __DLL__ __KERNEL_MODE__
+include $(FLMHOME)/e32abiv2.flm
+$(call vrestore)
+
+else
+$(error $e32abiv2var2.flm called with wrong TARGETTYPE (should be 'var2' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/emulator.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/emulator.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,226 +1,245 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- Emulator interfaces -->
-
-	<interface name="Emulator.flm" extends="base.flm" abstract="true">
-		<param name='DEFFILEKEYWORD'/>
-		<param name='OUTPUTPATH'/>
-		<param name='VARIANTPLATFORM'/>
-		<param name='PLATFORM' default='$(VARIANTPLATFORM)'/>
-		<param name='PRODUCT_INCLUDE'/>
-		<param name='RELEASEPATH'/>
-		<param name='REQUESTEDTARGETEXT' default=''/>
-		<param name='VARIANTTYPE'/>
-		<param name='SBSV1MAKE'/>
-		<param name='NMAKE'/>
-		<param name='NMAKEFLAGS'/>
-		<param name='FULLVARIANTPATH'/>
-		<param name='PLATMACROS.WINDOWS'/>
-		<param name='PLATMACROS.LINUX'/>
-		<param name='SUPPORTS_STDCPP_NEWLIB' default='1'/>
-	</interface>
-
-	<interface name="Emulator.mmp" extends="Emulator.flm" abstract="true">
-		<param name='BASEADDRESS' default=''/>
-		<param name='CAPABILITYFLAG1' default='00000000u'/>
-		<param name='CAPABILITYFLAG2' default='00000000u'/>
-		<param name='COPY_FOR_STATIC_LINKAGE' default='0'/>
-		<param name='DEBUGLIBRARY' default=''/>
-		<param name='DEFFILE' default=''/>
-		<param name='EFREEZE' default=''/>
-		<param name='EFREEZE_REMOVE_OPTION' default=''/>
-		<param name='EPOCALLOWDLLDATA' default='0'/>
-		<param name='EPOCHEAPSIZEMIN_DEC_KB' default=''/>
-		<param name='EPOCHEAPSIZEMAX_DEC_KB' default=''/>
-		<param name='EPOCPROCESSPRIORITY' default='Foreground'/>
-		<param name='EXPORTLIBRARY' default=''/>
-		<param name='EXPORTUNFROZEN' default=''/>
-		<param name='FIRSTLIB' default=''/>
-		<param name='LIBRARY' default=''/>
-		<param name='LIBRARY_DEBUG' default=''/>
-		<param name='LINKAS' default=''/>
-		<param name='LISTING_OPTION' default='-S'/>
-		<param name='MMPDEFS' default=''/>
-		<param name='NEWLIB' default=''/>
-		<param name='NOEXPORTLIBRARY' default='0'/>
-		<param name='NOSTDCPP' default=''/>
-		<param name='OPTION_CW' default=''/>
-		<param name='RESOLVED_DEFFILE' default=''/>
-		<param name='SECUREID' default=''/>
-		<param name='SOURCE' default=''/>
-		<param name='STATICLIBRARY' default=''/>
-		<param name='STDCPP' default=''/>
-		<param name='STDCPP_DEF' default=''/>
-		<param name='STDCPP_INCLUDE' default=''/>
-		<param name='STDCPP_WCHAR_DEF' default=''/>
-		<param name='SYSTEMINCLUDE' default=''/>
-		<param name='TARGET'/>
-		<param name='TARGETPATH'/>
-		<param name='TARGETTYPE'/>
-		<param name='TESTPATH' default=''/>
-		<param name='TESTCODE' default=''/>
-		<param name='TEST_OPTION' default=''/>
-		<param name='UID2' default='00000000'/>
-		<param name='UID3' default='00000000'/>
-		<param name='USE_TRACE_COMPILER' default=''/>
-		<param name='USERINCLUDE' default=''/>
-		<param name='VENDORID' default='00000000'/>
-		<param name='VERSIONHEX' default='00010000'/>
-		<param name='WIN32_HEADERS' default=''/>
-		<param name='WIN32_LIBRARY' default=''/>
-		<param name='WIN32_RESOURCE' default=''/>
-	</interface>
-
-	<interface name="Emulator.win32" extends="Emulator.mmp" abstract="true" flm="win32.flm">
-		<param name='CC'/>
-		<param name='CDEFS' default=''/>
-		<param name='CFLAGS' default=''/>
-		<param name='CW_DEFAULT_LIBS'/>
-		<param name='CW_RUNTIME_STATIC'/>
-		<param name='CW_RUNTIME_NONSTATIC'/>
-		<param name='DEFAULT_NORMAL_NEWLIB' default=''/>
-		<param name='DEFAULT_SYSTEM_NEWLIB' default=''/>
-		<param name='EXPORT_TYPE'/>
-		<param name='LINKPATH'/>
-		<param name='LFLAGS' default=''/>
-		<param name='NAME_LOOKUP' default=''/>
-		<param name='OPEN_ENVIRONMENT' default=''/>
-		<param name='OPT.ADDCOMMAND'/>
-		<param name='OPT.DEFINE'/>
-		<param name='OPT.DEFFILE'/>
-		<param name='OPT.DEPEND'/>
-		<param name='DEPEND_SKIP' default=''/>
-		<param name='OPT.EXPORT'/>
-		<param name='OPT.IMPORTLIB'/>
-		<param name='OPT.LISTING'/>
-		<param name='OPT.MENTRYPOINT'/>
-		<param name='OPT.MAINENTRYPOINT'/>
-		<param name='OPT.MAP'/>
-		<param name='OPT.NOCOMPACTIMPORTLIB'/>
-		<param name='OPT.NOENTRY'/>
-		<param name='OPT.NOSTDINC'/>
-		<param name='OPT.OUT'/>
-		<param name='OPT.PREINCLUDE'/>
-		<param name='OPT.RUNTIME'/>
-		<param name='OPT.SEARCH'/>
-		<param name='OPT.SHARED'/>
-		<param name='OPT.SPLITINCLUDE'/>
-		<param name='OPT.STDINC'/>
-		<param name='OPT.STDLIB'/>
-		<param name='OPT.SYSINCLUDE'/>
-		<param name='OPT.USERINCLUDE'/>
-		<param name='OPT.WARNINGS'/>
-		<param name='OPT.WCHAR'/>
-		<param name='PREPDEF'/>
-		<param name='RC'/>
-		<param name='MODULE'/>
-	</interface>
-
-	<interface name="Emulator.exe" extends="Emulator.win32" flm="win32exe.flm">
-		<param name='CHECKLIB' default=''/>
-		<param name='LD'/>
-		<param name='OPT.CHECKLIB.STDCPP'/>
-		<param name='OPT.CHECKLIB.SYMCPP'/>
-		<param name='OPT.CHECKLIB.WIN32'/>
-		<param name='OPT.HEAPCOMMIT'/>
-		<param name='OPT.HEAPRESERVE'/>
-		<param name='OPT.LIBFILE'/>
-		<param name='OPT.LIBPATH'/>
-		<param name='OPT.NOIMPLIB'/>
-	</interface>
-
-	<interface name="Emulator.stdexe" extends="Emulator.exe" flm="win32stdexe.flm">
-		<param name='TARGETTYPE' default="stdexe"/>
-		<param name='WCHARENTRYPOINT' default=""/>
-	</interface>
-
-	<interface name="Emulator.dll" extends="Emulator.win32" flm="win32dll.flm">
-		<param name='CHECKLIB' default=''/>
-		<param name='LD'/>
-		<param name='LFLAGS_INFGEN'/>
-		<param name='OPT.CHECKLIB.STDCPP'/>
-		<param name='OPT.CHECKLIB.SYMCPP'/>
-		<param name='OPT.CHECKLIB.WIN32'/>
-		<param name='OPT.HEAPCOMMIT'/>
-		<param name='OPT.HEAPRESERVE'/>
-		<param name='OPT.IMAGEBASE'/>
-		<param name='OPT.IMPLIB'/>
-		<param name='OPT.LIBFILE'/>
-		<param name='OPT.LIBPATH'/>
-		<param name='OPT.NOIMPLIB'/>
-		<param name='MAKEDEF'/>
-	</interface>
-
-	<interface name="Emulator.stddll" extends="Emulator.dll" flm="win32stddll.flm">
-		<param name='LFLAGS_SYMGEN'/>
-		<param name='SYMLOOKUPUTIL'/>
-		<param name='SYMLOOKUPARGS'/>
-		<param name='TARGETTYPE' default="stddll"/>
-	</interface>
-
-	<interface name="Emulator.implib" extends="Emulator.win32" flm="win32implib.flm">
-		<param name='LD'/>
-		<param name='OPT.IMPORTLIB'/>
-		<param name='PREPDEF'/>
-	</interface>
-
-	<interface name="Emulator.lib" extends="Emulator.win32" flm="win32lib.flm">
-		<param name='LD'/>
-		<param name='OPT.STATICLIBRARY'/>
-		<param name='OPT.LIBFILE'/>
-		<param name='OPT.LIBPATH'/>
-		<param name='OPT.NOIMPLIB'/>
-	</interface>
-
-	<interface name="Emulator.stdlib" extends="Emulator.lib" flm="win32stdlib.flm">
-		<param name='TARGETTYPE' default="stdlib"/>
-	</interface>
-
-	<interface name="Emulator.resource" extends="base.resource" flm="win32resource.flm">
-	</interface>
-
-	<interface name="Emulator.bitmap" extends="base.bitmap" flm="win32bitmap.flm">
-	</interface>
-
-	<interface name="Emulator.ani" extends="Emulator.dll" flm="win32ani.flm">
-	</interface>
-
-	<interface name="Emulator.exexp" extends="Emulator.dll" flm="win32exexp.flm">
-	</interface>
-
-	<interface name="Emulator.fsy" extends="Emulator.dll" flm="win32fsy.flm">
-	</interface>
-
-	<interface name="Emulator.kdll" extends="Emulator.dll" flm="win32kdll.flm">
-	</interface>
-
-	<interface name="Emulator.kext" extends="Emulator.dll" flm="win32kext.flm">
-	</interface>
-
-	<interface name="Emulator.klib" extends="Emulator.lib" flm="win32klib.flm">
-	</interface>
-
-	<interface name="Emulator.ldd" extends="Emulator.dll" flm="win32ldd.flm">
-	</interface>
-
-	<interface name="Emulator.none" extends="Emulator.mmp" flm="none.flm">
-	</interface>
-
-	<interface name="Emulator.pdd" extends="Emulator.dll" flm="win32pdd.flm">
-	</interface>
-
-	<interface name="Emulator.pdl" extends="Emulator.dll" flm="win32pdl.flm">
-	</interface>
-
-	<interface name="Emulator.plugin" extends="Emulator.dll" flm="win32plugin.flm">
-	</interface>
-
-	<interface name="Emulator.textnotifier2" extends="Emulator.dll" flm="win32textnotifier2.flm">
-	</interface>
-
-	<interface name="Emulator.var" extends="Emulator.dll" flm="win32var.flm">
-	</interface>
-
-	<interface name="Emulator.var2" extends="Emulator.dll" flm="win32var2.flm">
-	</interface>
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- Emulator interfaces -->
+
+	<interface name="Emulator.flm" extends="base.flm" abstract="true">
+		<param name='DEFFILEKEYWORD'/>
+		<param name='OUTPUTPATH'/>
+		<param name='VARIANTPLATFORM'/>
+		<param name='PLATFORM' default='$(VARIANTPLATFORM)'/>
+		<param name='PRODUCT_INCLUDE'/>
+		<param name='RELEASEPATH'/>
+		<param name='REQUESTEDTARGETEXT' default=''/>
+		<param name='VARIANTTYPE'/>
+		<param name='SBSV1MAKE'/>
+		<param name='NMAKE'/>
+		<param name='NMAKEFLAGS'/>
+		<param name='FULLVARIANTPATH'/>
+		<param name='PLATMACROS.WINDOWS'/>
+		<param name='PLATMACROS.LINUX'/>
+		<param name='SUPPORTS_STDCPP_NEWLIB' default='1'/>
+	</interface>
+
+	<interface name="Emulator.mmp" extends="Emulator.flm" abstract="true">
+		<param name='BASEADDRESS' default=''/>
+		<param name='CAPABILITYFLAG1' default='00000000u'/>
+		<param name='CAPABILITYFLAG2' default='00000000u'/>
+		<param name='COPY_FOR_STATIC_LINKAGE' default='0'/>
+		<param name='DEBUGLIBRARY' default=''/>
+		<param name='DEFFILE' default=''/>
+		<param name='EFREEZE' default=''/>
+		<param name='EFREEZE_REMOVE_OPTION' default=''/>
+		<param name='EPOCALLOWDLLDATA' default='0'/>
+		<param name='EPOCHEAPSIZEMIN_DEC_KB' default=''/>
+		<param name='EPOCHEAPSIZEMAX_DEC_KB' default=''/>
+		<param name='EPOCPROCESSPRIORITY' default='Foreground'/>
+		<param name='EXPORTLIBRARY' default=''/>
+		<param name='EXPORTUNFROZEN' default=''/>
+		<param name='FIRSTLIB' default=''/>
+		<param name='LIBRARY' default=''/>
+		<param name='LIBRARY_DEBUG' default=''/>
+		<param name='LINKAS' default=''/>
+		<param name='LISTING_OPTION' default='-S'/>
+		<param name='MMPDEFS' default=''/>
+		<param name='NEWLIB' default=''/>
+		<param name='NOEXPORTLIBRARY' default='0'/>
+		<param name='NOSTDCPP' default=''/>
+		<param name='OPTION_CW' default=''/>
+		<param name='RESOLVED_DEFFILE' default=''/>
+		<param name='SECUREID' default=''/>
+		<param name='SOURCE' default=''/>
+		<param name='STATICLIBRARY' default=''/>
+		<param name='STDCPP' default=''/>
+		<param name='STDCPP_DEF' default=''/>
+		<param name='STDCPP_INCLUDE' default=''/>
+		<param name='STDCPP_WCHAR_DEF' default=''/>
+		<param name='SYSTEMINCLUDE' default=''/>
+		<param name='TARGET'/>
+		<param name='TARGETPATH'/>
+		<param name='TARGETTYPE'/>
+		<param name='TESTPATH' default=''/>
+		<param name='TESTCODE' default=''/>
+		<param name='TEST_OPTION' default=''/>
+		<param name='UID2' default='00000000'/>
+		<param name='UID3' default='00000000'/>
+		<param name='USE_TRACE_COMPILER' default=''/>
+		<param name='USERINCLUDE' default=''/>
+		<param name='VENDORID' default='00000000'/>
+		<param name='VERSIONHEX' default='00010000'/>
+		<param name='WIN32_HEADERS' default=''/>
+		<param name='WIN32_LIBRARY' default=''/>
+		<param name='WIN32_RESOURCE' default=''/>
+	</interface>
+
+	<interface name="Emulator.win32" extends="Emulator.mmp" abstract="true" flm="win32.flm">
+		<param name='CC'/>
+		<param name='CDEFS' default=''/>
+		<param name='CFLAGS' default=''/>
+		<param name='CW_DEFAULT_LIBS'/>
+		<param name='CW_RUNTIME_STATIC'/>
+		<param name='CW_RUNTIME_NONSTATIC'/>
+		<param name='DEFAULT_NORMAL_NEWLIB' default=''/>
+		<param name='DEFAULT_SYSTEM_NEWLIB' default=''/>
+		<param name='EXPORT_TYPE'/>
+		<param name='LINKPATH'/>
+		<param name='LFLAGS' default=''/>
+		<param name='NAME_LOOKUP' default=''/>
+		<param name='OPEN_ENVIRONMENT' default=''/>
+		<param name='OPT.ADDCOMMAND'/>
+		<param name='OPT.DEFINE'/>
+		<param name='OPT.DEFFILE'/>
+		<param name='OPT.DEPEND'/>
+		<param name='OPT.EXPORT'/>
+		<param name='OPT.IMPORTLIB'/>
+		<param name='OPT.LISTING'/>
+		<param name='OPT.MENTRYPOINT'/>
+		<param name='OPT.MAINENTRYPOINT'/>
+		<param name='OPT.MAP'/>
+		<param name='OPT.NOCOMPACTIMPORTLIB'/>
+		<param name='OPT.NOENTRY'/>
+		<param name='OPT.NOSTDINC'/>
+		<param name='OPT.OUT'/>
+		<param name='OPT.PREINCLUDE'/>
+		<param name='OPT.RUNTIME'/>
+		<param name='OPT.SEARCH'/>
+		<param name='OPT.SHARED'/>
+		<param name='OPT.SPLITINCLUDE'/>
+		<param name='OPT.STDINC'/>
+		<param name='OPT.STDLIB'/>
+		<param name='OPT.SYSINCLUDE'/>
+		<param name='OPT.USERINCLUDE'/>
+		<param name='OPT.WARNINGS'/>
+		<param name='OPT.WCHAR'/>
+		<param name='PREPDEF'/>
+		<param name='RC'/>
+		<param name='MODULE'/>
+	</interface>
+
+	<interface name="Emulator.exe" extends="Emulator.win32" flm="win32exe.flm">
+		<param name='CHECKLIB' default=''/>
+		<param name='LD'/>
+		<param name='OPT.CHECKLIB.STDCPP'/>
+		<param name='OPT.CHECKLIB.SYMCPP'/>
+		<param name='OPT.CHECKLIB.WIN32'/>
+		<param name='OPT.HEAPCOMMIT'/>
+		<param name='OPT.HEAPRESERVE'/>
+		<param name='OPT.LIBFILE'/>
+		<param name='OPT.LIBPATH'/>
+		<param name='OPT.NOIMPLIB'/>
+	</interface>
+
+	<interface name="Emulator.stdexe" extends="Emulator.exe" flm="win32stdexe.flm">
+		<param name='TARGETTYPE' default="stdexe"/>
+		<param name='WCHARENTRYPOINT' default=""/>
+	</interface>
+
+	<interface name="Emulator.dll" extends="Emulator.win32" flm="win32dll.flm">
+		<param name='CHECKLIB' default=''/>
+		<param name='LD'/>
+		<param name='LFLAGS_INFGEN'/>
+		<param name='OPT.CHECKLIB.STDCPP'/>
+		<param name='OPT.CHECKLIB.SYMCPP'/>
+		<param name='OPT.CHECKLIB.WIN32'/>
+		<param name='OPT.HEAPCOMMIT'/>
+		<param name='OPT.HEAPRESERVE'/>
+		<param name='OPT.IMAGEBASE'/>
+		<param name='OPT.IMPLIB'/>
+		<param name='OPT.LIBFILE'/>
+		<param name='OPT.LIBPATH'/>
+		<param name='OPT.NOIMPLIB'/>
+		<param name='MAKEDEF'/>
+	</interface>
+
+	<interface name="Emulator.pdll" extends="Emulator.win32" flm="win32pdll.flm">
+		<param name='CHECKLIB' default=''/>
+		<param name='LD'/>
+		<param name='LFLAGS_INFGEN'/>
+		<param name='OPT.CHECKLIB.STDCPP'/>
+		<param name='OPT.CHECKLIB.SYMCPP'/>
+		<param name='OPT.CHECKLIB.WIN32'/>
+		<param name='OPT.HEAPCOMMIT'/>
+		<param name='OPT.HEAPRESERVE'/>
+		<param name='OPT.IMAGEBASE'/>
+		<param name='OPT.IMPLIB'/>
+		<param name='OPT.LIBFILE'/>
+		<param name='OPT.LIBPATH'/>
+		<param name='OPT.NOIMPLIB'/>
+		<param name='MAKEDEF'/>
+	</interface>
+
+	<interface name="Emulator.stddll" extends="Emulator.dll" flm="win32stddll.flm">
+		<param name='LFLAGS_SYMGEN'/>
+		<param name='SYMLOOKUPUTIL'/>
+		<param name='SYMLOOKUPARGS'/>
+		<param name='TARGETTYPE' default="stddll"/>
+	</interface>
+
+	<interface name="Emulator.implib" extends="Emulator.win32" flm="win32implib.flm">
+		<param name='LD'/>
+		<param name='OPT.IMPORTLIB'/>
+		<param name='PREPDEF'/>
+	</interface>
+
+	<interface name="Emulator.lib" extends="Emulator.win32" flm="win32lib.flm">
+		<param name='LD'/>
+		<param name='OPT.STATICLIBRARY'/>
+		<param name='OPT.LIBFILE'/>
+		<param name='OPT.LIBPATH'/>
+		<param name='OPT.NOIMPLIB'/>
+	</interface>
+
+	<interface name="Emulator.stdlib" extends="Emulator.lib" flm="win32stdlib.flm">
+		<param name='TARGETTYPE' default="stdlib"/>
+	</interface>
+
+	<interface name="Emulator.resource" extends="base.resource" flm="win32resource.flm">
+	</interface>
+
+	<interface name="Emulator.bitmap" extends="base.bitmap" flm="win32bitmap.flm">
+	</interface>
+
+	<interface name="Emulator.ani" extends="Emulator.dll" flm="win32ani.flm">
+	</interface>
+
+	<interface name="Emulator.exexp" extends="Emulator.dll" flm="win32exexp.flm">
+	</interface>
+
+	<interface name="Emulator.fsy" extends="Emulator.dll" flm="win32fsy.flm">
+	</interface>
+
+	<interface name="Emulator.kdll" extends="Emulator.dll" flm="win32kdll.flm">
+	</interface>
+
+	<interface name="Emulator.kext" extends="Emulator.dll" flm="win32kext.flm">
+	</interface>
+
+	<interface name="Emulator.klib" extends="Emulator.lib" flm="win32klib.flm">
+	</interface>
+
+	<interface name="Emulator.ldd" extends="Emulator.dll" flm="win32ldd.flm">
+	</interface>
+
+	<interface name="Emulator.none" extends="Emulator.mmp" flm="none.flm">
+	</interface>
+
+	<interface name="Emulator.pdd" extends="Emulator.dll" flm="win32pdd.flm">
+	</interface>
+
+	<interface name="Emulator.pdl" extends="Emulator.dll" flm="win32pdl.flm">
+	</interface>
+
+	<interface name="Emulator.plugin" extends="Emulator.dll" flm="win32plugin.flm">
+	</interface>
+
+	<interface name="Emulator.plugin3" extends="Emulator.dll" flm="win32plugin.flm">
+	</interface>
+
+	<interface name="Emulator.textnotifier2" extends="Emulator.dll" flm="win32textnotifier2.flm">
+	</interface>
+
+	<interface name="Emulator.var" extends="Emulator.dll" flm="win32var.flm">
+	</interface>
+
+	<interface name="Emulator.var2" extends="Emulator.dll" flm="win32var2.flm">
+	</interface>
+</build>
--- a/sbsv2/raptor/lib/flm/extensions.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/extensions.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,47 +1,47 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- Extension interfaces : replacements for Template Extension Makefiles -->
-
-	<interface name="Symbian.UserFLM" extends="base.flm" abstract="true">
-		<param name='EPOCROOT'/>
-		<param name='PRODUCT_INCLUDE'/>
-		<param name='EPOCBLD'/>
-		<param name='TO_BLDINF'/>
-		<param name='EXTENSION_ROOT'/>
-		<param name='PLATFORM'/>
-		<param name='PLATFORM_PATH'/>
-		<param name='CFG'/>
-		<param name='CFG_PATH'/>
-		<param name='PERL'/>
-	</interface>
-
-	<interface name="Symbian.KernelFLM" extends="Symbian.UserFLM" abstract="true">
-		<param name='CC'/>
-		<param name='LD'/>
-		<param name='ASM'/>
-		<param name='FROMELF'/>		
-	</interface>
-	
-	<interface name="tools.stlport" extends="Symbian.UserFLM" flm="tools/stlport.flm">
-		<param name="STLPORT_VERSION"/>
-		<param name="STL_REL_LIB_NAME"/>
-		<param name="STL_DEB_LIB_NAME"/>
-		<param name="SOURCE_ARCHIVE"/>
-	</interface>
-
-	<interface name="converged-comms.createcommdbs" extends="Symbian.UserFLM" flm="converged-comms/createcommdbs.flm">
-		<param name="SRCDIR"/>
-	</interface>
-	<interface name="application-protocols.buildstubsis" extends="Symbian.UserFLM" flm="tools/buildstubsis.flm">
-		<param name="SISNAME"/>
-		<param name="SRCDIR"/>
-	</interface>
-	<!-- -->
-	<interface name="app-services.buildstubsis" extends="application-protocols.buildstubsis" flm="tools/buildstubsis.flm">
-	</interface>
-
-	<interface name="converged-comms.installdefaultcommdb" extends="Symbian.UserFLM" flm="converged-comms/installdefaultcommdb.flm">
-
-	</interface>
-
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- Extension interfaces : replacements for Template Extension Makefiles -->
+
+	<interface name="Symbian.UserFLM" extends="base.flm" abstract="true">
+		<param name='EPOCROOT'/>
+		<param name='PRODUCT_INCLUDE'/>
+		<param name='EPOCBLD'/>
+		<param name='TO_BLDINF'/>
+		<param name='EXTENSION_ROOT'/>
+		<param name='PLATFORM'/>
+		<param name='PLATFORM_PATH'/>
+		<param name='CFG'/>
+		<param name='CFG_PATH'/>
+		<param name='PERL'/>
+	</interface>
+
+	<interface name="Symbian.KernelFLM" extends="Symbian.UserFLM" abstract="true">
+		<param name='CC'/>
+		<param name='LD'/>
+		<param name='ASM'/>
+		<param name='FROMELF'/>		
+	</interface>
+	
+	<interface name="tools.stlport" extends="Symbian.UserFLM" flm="tools/stlport.flm">
+		<param name="STLPORT_VERSION"/>
+		<param name="STL_REL_LIB_NAME"/>
+		<param name="STL_DEB_LIB_NAME"/>
+		<param name="SOURCE_ARCHIVE"/>
+	</interface>
+
+	<interface name="converged-comms.createcommdbs" extends="Symbian.UserFLM" flm="converged-comms/createcommdbs.flm">
+		<param name="SRCDIR"/>
+	</interface>
+	<interface name="application-protocols.buildstubsis" extends="Symbian.UserFLM" flm="tools/buildstubsis.flm">
+		<param name="SISNAME"/>
+		<param name="SRCDIR"/>
+	</interface>
+	<!-- -->
+	<interface name="app-services.buildstubsis" extends="application-protocols.buildstubsis" flm="tools/buildstubsis.flm">
+	</interface>
+
+	<interface name="converged-comms.installdefaultcommdb" extends="Symbian.UserFLM" flm="converged-comms/installdefaultcommdb.flm">
+
+	</interface>
+
+</build>
--- a/sbsv2/raptor/lib/flm/final.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/final.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,30 +1,30 @@
-#
-# 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: 
-# final include file : this is included at the end of
-# all generated makefiles
-# INPUTS : assumes OSTYPE and FLMHOME are set.
-#
-
-# The final makefile is not a once-per-build file
-# if the make tree is split into many files then
-# final must be "included" many times
-
-# Create all remaining buffered directories
-#
-$(call makepathfinalise)
-
-# For users of SBSv2 who wish to add in their own final settings
-# without modifying this file:
--include $(FLMHOME)/user/final.mk
+#
+# 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: 
+# final include file : this is included at the end of
+# all generated makefiles
+# INPUTS : assumes OSTYPE and FLMHOME are set.
+#
+
+# The final makefile is not a once-per-build file
+# if the make tree is split into many files then
+# final must be "included" many times
+
+# Create all remaining buffered directories
+#
+$(call makepathfinalise)
+
+# For users of SBSv2 who wish to add in their own final settings
+# without modifying this file:
+-include $(FLMHOME)/user/final.mk
--- a/sbsv2/raptor/lib/flm/flmtools.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/flmtools.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,300 +1,300 @@
-#
-# 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: 
-# Tools for use in FLMs - common macros and variables
-#
-
-ifeq ($(FLMTOOLS.MK),)
-FLMTOOLS.MK:=included
-
-CHAR_COMMA:=,
-CHAR_SEMIC:=;
-CHAR_COLON:=:
-CHAR_BLANK:=
-#the BLANK BLANK trick saves us from clever text editrors that remove spaces at the end of a line
-CHAR_SPACE:=$(BLANK) $(BLANK)
-CHAR_DQUOTE:="
-CHAR_QUOTE:='
-CHAR_LBRACKET:=(
-CHAR_RBRACKET:=)
-CHAR_DOLLAR:=$
-
-#'" # This comment makes syntax highlighting work again. Leave it here please!
-
-# A macro to ensure that the shell does not 
-# interpret brackets in a command
-define shEscapeBrackets
-$(subst $(CHAR_LBRACKET),\$(CHAR_LBRACKET),$(subst $(CHAR_RBRACKET),\$(CHAR_RBRACKET),$(1)))
-endef
-
-# A macro to protect quotes from shell expansion
-define shEscapeQuotes
-$(subst $(CHAR_QUOTE),\$(CHAR_QUOTE),$(subst $(CHAR_DQUOTE),\$(CHAR_DQUOTE),$(1)))
-endef
-
-# Protect against shell expansion
-define shEscape
-$(call shEscapeBrackets,$(call shEscapeQuotes,$(1)))
-endef
-
-# A macro to escape spaces for use in rule targets or dependencies
-define ruleEscape
-$(subst $(CHAR_SPACE),\$(CHAR_SPACE),$(1))
-endef
-
-# A macro for turning a list into a concatenated string
-# 1st parameter is the separator to use, second is the list
-# e.g. $(call concat,:,/sbin /usr/sbin /usr/local/sbin /bin /usr/bin /usr/local/bin)
-# would create the string
-#   /sbin:/usr/sbin:/usr/local/sbin:/bin:/usr/bin:/usr/local/bin
-# It has to be recursive to manage to create a string from a list
-define concat
-$(if $(word 2,$(2)),$(firstword $(2))$(1)$(call concat,$(1),$(wordlist 2,$(words $(2)),$(2))),$(2))
-endef
-
-# A macro for converting a string to lowercase
-lowercase_TABLE:=A,a B,b C,c D,d E,e F,f G,g H,h I,i J,j K,k L,l M,m N,n O,o P,p Q,q R,r S,s T,t U,u V,v W,w X,x Y,y Z,z
-
-define lowercase_internal
-$(if $1,$$(subst $(firstword $1),$(call lowercase_internal,$(wordlist 2,$(words $1),$1),$2)),$2)
-endef
-
-define lowercase
-$(eval lowercase_RESULT:=$(call lowercase_internal,$(lowercase_TABLE),$1))$(lowercase_RESULT)
-endef
-
-# A macro for converting a string to uppercase
-uppercase_TABLE:=a,A b,B c,C d,D e,E f,F g,G h,H i,I j,J k,K l,L m,M n,N o,O p,P q,Q r,R s,S t,T u,U v,V w,W x,X y,Y z,Z
-
-define uppercase_internal
-$(if $1,$$(subst $(firstword $1),$(call uppercase_internal,$(wordlist 2,$(words $1),$1),$2)),$2)
-endef
-
-define uppercase
-$(eval uppercase_RESULT:=$(call uppercase_internal,$(uppercase_TABLE),$1))$(uppercase_RESULT)
-endef
-
-# A macro for removing duplicate tokens from a list 
-# whilst retaining the list's order
-define uniq
-$(if $(1),$(info $(words $(1)) $(1))\
-$(firstword $(1))$(call uniq,$(filter-out $(firstword $(1)),$(wordlist 2,$(words $(1)),$(1))))\
-,)
-endef
-
-# A macro for enclosing all list elements in some kind of quote or bracket
-define enclose
-$(foreach ITEM,$(2),$(1)$(ITEM)$(1))
-endef
-
-# A macro enclosing all list elements in double quotes and removing escapes
-define dblquote
-$(subst \,,$(call enclose,$(CHAR_DQUOTE),$(1)))
-endef
-
-# A macro enclosing a single item in double quotes, so that spaces can be quoted
-define dblquoteitem
-$(if $(1),$(CHAR_DQUOTE)$(1)$(CHAR_DQUOTE),)
-endef
-
-# A macro to add a prefix to a list of items, while putting quotes around each
-# item so prefixed, to allow spaces in the prefix.
-define addquotedprefix
-$(addprefix $(CHAR_DQUOTE)$(1),$(addsuffix $(CHAR_DQUOTE),$(2)))
-endef
-
-# A macro enclosing all list elements in single quotes and prepending a string
-# basically to turn a list like:
-#    LINUX TOOLS EXP=_declspec(export) NODEBUG
-# into:
-#    -D'LINUX' -D'TOOLS' -D'EXP=_declspec(export)' -DNODEBUG
-define makemacrodef
-$(strip $(patsubst %,$1'%',$2))
-endef
-
-# Make a (filename) string safe for use as a variable name
-define sanitise
-$(subst /,_,$(subst :,_,$(1)))
-endef
-
-# A variation on several macros implemented directly in FLMs, this takes a filename and a list
-# of "words" and pumps groups of 10 words at a time into the file.  Its main use is the creation
-# of command/response files for tools that need to avoid blowing command line length limits
-# when referencing long lists of absolutely pathed files.
-define groupin10infile
-	$(if $2,@echo -e $(foreach L,$(wordlist 1,10,$2),"$(L)\\n") >>$1,)
-	$(if $2,$(call groupin10infile,$1,$(wordlist 11,$(words $2),$2)),@true)
-endef
-
-## DEBUGGING Macros ######################################
-
-# A macro to help with debugging FLMs by printing out variables specified in the FLMDEBUG variable
-define flmdebug
-$(if $(FLMDEBUG),@echo -e "<flmdebug>\\n $(foreach VAR,$(FLMDEBUG),$(VAR):=$($(VAR))\\n)</flmdebug>",)
-endef
-
-define flmdebug2
-flmdebug2_OUT:=$(if $(FLMDEBUG),$(shell echo -e "<flmdebug>\\n $(foreach VAR,$(FLMDEBUG),$(VAR):=$($(VAR))\\n)</flmdebug>" 1>&2),)
-endef
-
-## Path handling tools ###################################
-
-ifeq ($(OSTYPE),cygwin)
-
-SPACESLASH:=$(CHAR_SPACE)/
-SPACESLASH2:=$(CHAR_SPACE)\/
-SPACEDSLASH:=$(CHAR_SPACE)//
-# How lists of directories are separated on this OS:
-DIRSEP:=$(CHAR_SEMIC)
-
-define slashprotect
-$(subst $(SPACESLASH),$(SPACESLASH2),$(1))
-endef
-
-define pathprep
-$(subst $(SPACESLASH),$(SPACEDSLASH),$(1))
-endef
-
-else
-
-# How lists of directories are separated on this OS:
-DIRSEP:=$(CHAR_COLON)
-
-define slashprotect
-$(1)
-endef
-
-define pathprep
-$(1)
-endef
-
-endif
-
-# Path separator (always / in make)
-PATHSEP=/
-
-## Source to object file mapping #########################
-
-## Converting a list of source files to a list of object files without altering their
-## relative order.  Also deals with multiple file types mapping to the same object type
-## e.g. .CPP and .cpp and .c++ all map to .o
-define allsuffixsubst_internal
-$(if $1,$$(patsubst %$(firstword $1),%$2,$(call allsuffixsubst_internal,$(wordlist 2,$(words $1),$1),$2,$3)),$3)
-endef
-
-# $1 - the list of suffixes to replace
-# $2 - the suffix to replace them with
-# $3 - the list of strings to perform the replacement on
-define allsuffixsubst
-$(eval allsuffixsubst_RESULT:=$(call allsuffixsubst_internal,$1,$2,$3))$(allsuffixsubst_RESULT)
-endef
-
-## extractfilesoftype ##
-# $(1) is the list of types to extract e.g. cpp cxx CPP
-# $(2) is the list of files to select from
-define extractfilesoftype
-$(foreach EXT,$(1),$(filter %$(EXT),$(2)))
-endef
-
-## extractandmap ##
-# $(1) is the list of types e.g. cpp cxx CPP
-# $(2) is the extension to map to e.g. .o or .ARMV5.lst oe _.cpp
-# $(3) is the list of files to select from
-# This functon turns a list like 'fred.cpp bob.c++' into 'fred.o bob.o'
-define extractandmap
-$(foreach EXT,$(1),$(patsubst %$(EXT),%$(2),$(filter %$(EXT),$(3))))
-endef
-
-## relocatefiles ##
-# $(1) directory to relocate them in
-# $(2) list of files to relocate
-define relocatefiles
-$(patsubst %,$(1)/%,$(notdir $(2)))
-endef
-
-
-## Get stack handling code (for calls to FLMS which don't destroy variables)
-include $(FLMHOME)/stack.mk
-
-## Allow flm rules to be tagged and enable FORCESUCCESS feature etc
-include $(FLMHOME)/taggedrules.mk
-
-## Get boolean tools e.g. that implement the equals macro.
-include $(FLMHOME)/booleanlogic.mk
-
-## Macros for writing recipes without needing to know eval
-#
-# an ordinary recipe, for example,
-#
-# $(call raptor_recipe,name,$(TARGET),$(PREREQUISITES),$(COMMAND))
-#
-define raptor_recipe
-$(eval $2: $3
-	$(call startrule,$1) $4 $(call endrule,$1)
-)
-endef
-#
-# a phony recipe (double colon rule). Making a separate macro with an uglier
-# name will hopefully discourage people from using this unless they need to,
-# for example,
-#
-# $(call raptor_phony_recipe,name,ALL,,$(COMMAND))
-#
-define raptor_phony_recipe
-$(eval $2:: $3
-	$(call startrule,$1) $4 $(call endrule,$1)
-)
-endef
-
-################################################################################
-## Test code to allow this makefile fragment to be tested in a standalone manner
-##
-## example:
-##   FLMHOME=./ make -f flmtools.mk  STANDALONE_TEST=1 
-##
-
-ifneq ($(STANDALONE_TEST),)
-
-test::
-	@echo "macros"
-	test  "$(call concat,:,CON CAT EN ATED)" == "CON:CAT:EN:ATED" 
-	test  "$(call enclose,$(CHAR_QUOTE),THESE WORDS ARE QUOTED)" == "'THESE' 'WORDS' 'ARE' 'QUOTED'" 
-	echo $(SHELL)
-	test  '$(call dblquote,THESE WORDS ARE DOUBLEQUOTED)' == '"THESE" "WORDS" "ARE" "DOUBLEQUOTED"'
-	echo  $(call dqnp,/c/fred /d/alice /blah/blah)
-	@echo ""
-
-
-test::
-	@echo lowercase macro
-	test '$(call lowercase,ABCDEFGHIJKLMNOPQRSTUVWXYZ AA BB CC)' == 'abcdefghijklmnopqrstuvwxyz aa bb cc'
-
-define lowercase_internal
-$(if $1,$$(subst $(firstword $1),$(call lowercase_internal,$(wordlist 2,$(words $1),$1),$2)),$2)
-endef
-
-define lowercase
-$(eval lowercase_RESULT:=$(call lowercase_internal,$(lowercase_TABLE),$1))$(lowercase_RESULT)
-endef
-
-	test '$(call pathprep,--apcs /inter)' == '--apcs //inter'
-	
-test::
-	@echo "pathprep macro"
-	test '$(call pathprep,--apcs /inter)' == '--apcs //inter'
-	test '$(call pathprep,blah theone/or/theother)' == 'blah theone/or/theother'
-
-endif
-endif
-
+#
+# 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: 
+# Tools for use in FLMs - common macros and variables
+#
+
+ifeq ($(FLMTOOLS.MK),)
+FLMTOOLS.MK:=included
+
+CHAR_COMMA:=,
+CHAR_SEMIC:=;
+CHAR_COLON:=:
+CHAR_BLANK:=
+#the BLANK BLANK trick saves us from clever text editrors that remove spaces at the end of a line
+CHAR_SPACE:=$(BLANK) $(BLANK)
+CHAR_DQUOTE:="
+CHAR_QUOTE:='
+CHAR_LBRACKET:=(
+CHAR_RBRACKET:=)
+CHAR_DOLLAR:=$
+
+#'" # This comment makes syntax highlighting work again. Leave it here please!
+
+# A macro to ensure that the shell does not 
+# interpret brackets in a command
+define shEscapeBrackets
+$(subst $(CHAR_LBRACKET),\$(CHAR_LBRACKET),$(subst $(CHAR_RBRACKET),\$(CHAR_RBRACKET),$(1)))
+endef
+
+# A macro to protect quotes from shell expansion
+define shEscapeQuotes
+$(subst $(CHAR_QUOTE),\$(CHAR_QUOTE),$(subst $(CHAR_DQUOTE),\$(CHAR_DQUOTE),$(1)))
+endef
+
+# Protect against shell expansion
+define shEscape
+$(call shEscapeBrackets,$(call shEscapeQuotes,$(1)))
+endef
+
+# A macro to escape spaces for use in rule targets or dependencies
+define ruleEscape
+$(subst $(CHAR_SPACE),\$(CHAR_SPACE),$(1))
+endef
+
+# A macro for turning a list into a concatenated string
+# 1st parameter is the separator to use, second is the list
+# e.g. $(call concat,:,/sbin /usr/sbin /usr/local/sbin /bin /usr/bin /usr/local/bin)
+# would create the string
+#   /sbin:/usr/sbin:/usr/local/sbin:/bin:/usr/bin:/usr/local/bin
+# It has to be recursive to manage to create a string from a list
+define concat
+$(if $(word 2,$(2)),$(firstword $(2))$(1)$(call concat,$(1),$(wordlist 2,$(words $(2)),$(2))),$(2))
+endef
+
+# A macro for converting a string to lowercase
+lowercase_TABLE:=A,a B,b C,c D,d E,e F,f G,g H,h I,i J,j K,k L,l M,m N,n O,o P,p Q,q R,r S,s T,t U,u V,v W,w X,x Y,y Z,z
+
+define lowercase_internal
+$(if $1,$$(subst $(firstword $1),$(call lowercase_internal,$(wordlist 2,$(words $1),$1),$2)),$2)
+endef
+
+define lowercase
+$(eval lowercase_RESULT:=$(call lowercase_internal,$(lowercase_TABLE),$1))$(lowercase_RESULT)
+endef
+
+# A macro for converting a string to uppercase
+uppercase_TABLE:=a,A b,B c,C d,D e,E f,F g,G h,H i,I j,J k,K l,L m,M n,N o,O p,P q,Q r,R s,S t,T u,U v,V w,W x,X y,Y z,Z
+
+define uppercase_internal
+$(if $1,$$(subst $(firstword $1),$(call uppercase_internal,$(wordlist 2,$(words $1),$1),$2)),$2)
+endef
+
+define uppercase
+$(eval uppercase_RESULT:=$(call uppercase_internal,$(uppercase_TABLE),$1))$(uppercase_RESULT)
+endef
+
+# A macro for removing duplicate tokens from a list 
+# whilst retaining the list's order
+define uniq
+$(if $(1),$(info $(words $(1)) $(1))\
+$(firstword $(1))$(call uniq,$(filter-out $(firstword $(1)),$(wordlist 2,$(words $(1)),$(1))))\
+,)
+endef
+
+# A macro for enclosing all list elements in some kind of quote or bracket
+define enclose
+$(foreach ITEM,$(2),$(1)$(ITEM)$(1))
+endef
+
+# A macro enclosing all list elements in double quotes and removing escapes
+define dblquote
+$(subst \,,$(call enclose,$(CHAR_DQUOTE),$(1)))
+endef
+
+# A macro enclosing a single item in double quotes, so that spaces can be quoted
+define dblquoteitem
+$(if $(1),$(CHAR_DQUOTE)$(1)$(CHAR_DQUOTE),)
+endef
+
+# A macro to add a prefix to a list of items, while putting quotes around each
+# item so prefixed, to allow spaces in the prefix.
+define addquotedprefix
+$(addprefix $(CHAR_DQUOTE)$(1),$(addsuffix $(CHAR_DQUOTE),$(2)))
+endef
+
+# A macro enclosing all list elements in single quotes and prepending a string
+# basically to turn a list like:
+#    LINUX TOOLS EXP=_declspec(export) NODEBUG
+# into:
+#    -D'LINUX' -D'TOOLS' -D'EXP=_declspec(export)' -DNODEBUG
+define makemacrodef
+$(strip $(patsubst %,$1'%',$2))
+endef
+
+# Make a (filename) string safe for use as a variable name
+define sanitise
+$(subst /,_,$(subst :,_,$(1)))
+endef
+
+# A variation on several macros implemented directly in FLMs, this takes a filename and a list
+# of "words" and pumps groups of 10 words at a time into the file.  Its main use is the creation
+# of command/response files for tools that need to avoid blowing command line length limits
+# when referencing long lists of absolutely pathed files.
+define groupin10infile
+	$(if $2,@echo -e $(foreach L,$(wordlist 1,10,$2),"$(L)\\n") >>$1,)
+	$(if $2,$(call groupin10infile,$1,$(wordlist 11,$(words $2),$2)),@true)
+endef
+
+## DEBUGGING Macros ######################################
+
+# A macro to help with debugging FLMs by printing out variables specified in the FLMDEBUG variable
+define flmdebug
+$(if $(FLMDEBUG),@echo -e "<flmdebug>\\n $(foreach VAR,$(FLMDEBUG),$(VAR):=$($(VAR))\\n)</flmdebug>",)
+endef
+
+define flmdebug2
+flmdebug2_OUT:=$(if $(FLMDEBUG),$(shell echo -e "<flmdebug>\\n $(foreach VAR,$(FLMDEBUG),$(VAR):=$($(VAR))\\n)</flmdebug>" 1>&2),)
+endef
+
+## Path handling tools ###################################
+
+ifeq ($(OSTYPE),cygwin)
+
+SPACESLASH:=$(CHAR_SPACE)/
+SPACESLASH2:=$(CHAR_SPACE)\/
+SPACEDSLASH:=$(CHAR_SPACE)//
+# How lists of directories are separated on this OS:
+DIRSEP:=$(CHAR_SEMIC)
+
+define slashprotect
+$(subst $(SPACESLASH),$(SPACESLASH2),$(1))
+endef
+
+define pathprep
+$(subst $(SPACESLASH),$(SPACEDSLASH),$(1))
+endef
+
+else
+
+# How lists of directories are separated on this OS:
+DIRSEP:=$(CHAR_COLON)
+
+define slashprotect
+$(1)
+endef
+
+define pathprep
+$(1)
+endef
+
+endif
+
+# Path separator (always / in make)
+PATHSEP=/
+
+## Source to object file mapping #########################
+
+## Converting a list of source files to a list of object files without altering their
+## relative order.  Also deals with multiple file types mapping to the same object type
+## e.g. .CPP and .cpp and .c++ all map to .o
+define allsuffixsubst_internal
+$(if $1,$$(patsubst %$(firstword $1),%$2,$(call allsuffixsubst_internal,$(wordlist 2,$(words $1),$1),$2,$3)),$3)
+endef
+
+# $1 - the list of suffixes to replace
+# $2 - the suffix to replace them with
+# $3 - the list of strings to perform the replacement on
+define allsuffixsubst
+$(eval allsuffixsubst_RESULT:=$(call allsuffixsubst_internal,$1,$2,$3))$(allsuffixsubst_RESULT)
+endef
+
+## extractfilesoftype ##
+# $(1) is the list of types to extract e.g. cpp cxx CPP
+# $(2) is the list of files to select from
+define extractfilesoftype
+$(foreach EXT,$(1),$(filter %$(EXT),$(2)))
+endef
+
+## extractandmap ##
+# $(1) is the list of types e.g. cpp cxx CPP
+# $(2) is the extension to map to e.g. .o or .ARMV5.lst oe _.cpp
+# $(3) is the list of files to select from
+# This functon turns a list like 'fred.cpp bob.c++' into 'fred.o bob.o'
+define extractandmap
+$(foreach EXT,$(1),$(patsubst %$(EXT),%$(2),$(filter %$(EXT),$(3))))
+endef
+
+## relocatefiles ##
+# $(1) directory to relocate them in
+# $(2) list of files to relocate
+define relocatefiles
+$(patsubst %,$(1)/%,$(notdir $(2)))
+endef
+
+
+## Get stack handling code (for calls to FLMS which don't destroy variables)
+include $(FLMHOME)/stack.mk
+
+## Allow flm rules to be tagged and enable FORCESUCCESS feature etc
+include $(FLMHOME)/taggedrules.mk
+
+## Get boolean tools e.g. that implement the equals macro.
+include $(FLMHOME)/booleanlogic.mk
+
+## Macros for writing recipes without needing to know eval
+#
+# an ordinary recipe, for example,
+#
+# $(call raptor_recipe,name,$(TARGET),$(PREREQUISITES),$(COMMAND))
+#
+define raptor_recipe
+$(eval $2: $3
+	$(call startrule,$1) $4 $(call endrule,$1)
+)
+endef
+#
+# a phony recipe (double colon rule). Making a separate macro with an uglier
+# name will hopefully discourage people from using this unless they need to,
+# for example,
+#
+# $(call raptor_phony_recipe,name,ALL,,$(COMMAND))
+#
+define raptor_phony_recipe
+$(eval $2:: $3
+	$(call startrule,$1) $4 $(call endrule,$1)
+)
+endef
+
+################################################################################
+## Test code to allow this makefile fragment to be tested in a standalone manner
+##
+## example:
+##   FLMHOME=./ make -f flmtools.mk  STANDALONE_TEST=1 
+##
+
+ifneq ($(STANDALONE_TEST),)
+
+test::
+	@echo "macros"
+	test  "$(call concat,:,CON CAT EN ATED)" == "CON:CAT:EN:ATED" 
+	test  "$(call enclose,$(CHAR_QUOTE),THESE WORDS ARE QUOTED)" == "'THESE' 'WORDS' 'ARE' 'QUOTED'" 
+	echo $(SHELL)
+	test  '$(call dblquote,THESE WORDS ARE DOUBLEQUOTED)' == '"THESE" "WORDS" "ARE" "DOUBLEQUOTED"'
+	echo  $(call dqnp,/c/fred /d/alice /blah/blah)
+	@echo ""
+
+
+test::
+	@echo lowercase macro
+	test '$(call lowercase,ABCDEFGHIJKLMNOPQRSTUVWXYZ AA BB CC)' == 'abcdefghijklmnopqrstuvwxyz aa bb cc'
+
+define lowercase_internal
+$(if $1,$$(subst $(firstword $1),$(call lowercase_internal,$(wordlist 2,$(words $1),$1),$2)),$2)
+endef
+
+define lowercase
+$(eval lowercase_RESULT:=$(call lowercase_internal,$(lowercase_TABLE),$1))$(lowercase_RESULT)
+endef
+
+	test '$(call pathprep,--apcs /inter)' == '--apcs //inter'
+	
+test::
+	@echo "pathprep macro"
+	test '$(call pathprep,--apcs /inter)' == '--apcs //inter'
+	test '$(call pathprep,blah theone/or/theother)' == 'blah theone/or/theother'
+
+endif
+endif
+
--- a/sbsv2/raptor/lib/flm/gccxml.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/gccxml.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,257 +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:
-# All targets Function Like Makefile (FLM) supporting the execution of
-# gccxml_cc1plus on source, the creation of project and resource descriptive XML files
-# and packaging into an appropriate archive for CDB processing.
-#
-#
-
-
-# passed in values, stripped of whitespace
-DEFFILE:=$(strip $(DEFFILE))
-LINKAS:=$(strip $(LINKAS))
-UID1:=$(strip $(UID1))
-UID2:=$(strip $(UID2))
-UID3:=$(strip $(UID3))
-
-# local variables
-CREATABLEPATHS:=
-CLEANTARGETS:=
-RELEASABLES:=
-STDCPP_BUILD:=
-CIAFILEEXTENSIONS:=%.CIA %.cia %.Cia %.cIa %.cIA %.ciA %.CIa %.CiA
-
-ROOTBLDPATH:=$(OUTPUTPATH)/gccxml
-VARIANTBLDPATH:=$(OUTPUTPATH)/$(FULLVARIANTPATH)
-ROOTRELEASEPATH:=$(RELEASEPATH)/gccxml
-VARIANTRELEASEPATH:=$(RELEASEPATH)/$(FULLVARIANTPATH)
-
-CREATABLEPATHS:=$(CREATABLEPATHS) $(VARIANTBLDPATH) $(VARIANTRELEASEPATH) $(ROOTBLDPATH) $(ROOTRELEASEPATH)
-
-# type-specific definitions
-BASE_TYPE:=dll
-TARGET_MACRO:=__DLL__
-ifneq ($(findstring exe,$(TARGETTYPE)),)
-  BASE_TYPE:=exe
-  TARGET_MACRO:=__EXE__
-endif
-ifneq ($(findstring lib,$(TARGETTYPE)),)
-  BASE_TYPE:=lib
-  TARGET_MACRO:=
-endif
-
-# utility functions
-# returns absolutely-pathed temporary build filenames based solely on the basename of the source file, but with an additional "_" for .cia files
-# $(1) input source file list
-# $(2) output file extension
-define mapsource2output
-  $(foreach SOURCEFILE,$(1),$(patsubst %, $(VARIANTBLDPATH)/%, $(basename $(notdir $(SOURCEFILE)))$(if $(filter $(CIAFILEEXTENSIONS),$(SOURCEFILE)),_,)$(2)))
-endef
-
-# returns absolutely-pathed temporary build filenames based on the full resource filename
-# $(1) input resource file list
-# $(2) output file extension
-define mapresource2output
-  $(patsubst %, $(ROOTBLDPATH)/%, $(addsuffix $(2),$(notdir $(1))))
-endef
-
-# calls a tool multiple times with grouped arguments
-# $(1) tool to call with any non-variable arguments
-# $(2) list of further variable arguments to group in 150 element calls
-define groupcallin50
-	$(if $2,$1 $(foreach L,$(wordlist 1,50,$2),$(L)),)
-	$(if $2,$(call groupcallin50,$1,$(wordlist 51,$(words $2),$2)),true)
-endef
-
-# echos content to a file in groups performing optional search/replace based on passed args
-# $(1) template line with optional __VERBATIM__, __PATH__, __FILENAME__ replacements
-# $(2) list of pathed filenames to be batch processed and that can be used for template replacements
-# $(3) output file
-define groupreplacein50infile
-	$(if $2,@echo -e $(foreach L,$(wordlist 1,50,$2),"$(subst __VERBATIM__,$(L),$(subst __PATH__,$(dir $(L)),$(subst __FILENAME__,$(notdir $(L)),$1)))\\n") >>$3,)
-	$(if $2,$(call groupreplacein50infile,$1,$(wordlist 51,$(words $2),$2),$3),@true)
-endef
-
-# targets
-INCLUDESFILE:=$(ROOTRELEASEPATH)/includeheaders.txt
-MMPXMLFILE:=$(ROOTBLDPATH)/$(notdir $(PROJECT_META)).xml
-SRCXMLFILES:=$(call mapsource2output,$(SOURCE),.xml)
-RFIFILES:=$(call mapresource2output,$(RESOURCEFILES),.rfi)
-DEPFILES:=$(call mapsource2output,$(SOURCE),.xml.d)
-TEMPGXPARCHIVE:=$(VARIANTBLDPATH)/$(TARGET)$(BASE_TYPE).gxp
-GXPARCHIVE:=$(VARIANTRELEASEPATH)/$(TARGET)$(BASE_TYPE).gxp
-
-CLEANTARGETS:=$(CLEANTARGETS) $(MMPXMLFILE) $(SRCXMLFILES) $(DEPFILES) $(TEMPGXPARCHIVE) $(GXPARCHIVE)
-RELEASABLES:=$(RELEASABLES) $(GXPARCHIVE)
-
-# Deduce whether we should be performing a build with standard CPP characteristics
-# This operates differently per-OS release, although OE TARGETTYPEs always build with standard CPP traits
-ifeq ($(OPEN_ENVIRONMENT),1)
-  STDCPP_BUILD:=1
-endif
-
-ifeq ($(SUPPORTS_STDCPP_NEWLIB),1)
-  ifeq ($(NOSTDCPP),1)
-    STDCPP_BUILD:=
-  else
-    ifeq ($(STDCPP),1)
-      STDCPP_BUILD:=1
-    endif
-  endif
-endif
-
-ifeq ($(STDCPP_BUILD),1)
-  CDEFS:=$(CDEFS) $(STDCPP_DEF)
-  SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(STDCPP_INCLUDE)
-endif
-
-CDEFS:=$(CDEFS) $(TARGET_DEFS)
-SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(TARGET_INCLUDES)
-
-# include paths
-UINCLUDE:=$(patsubst %,$(OPT.USERINCLUDE)%,$(USERINCLUDE))
-SINCLUDE:=$(patsubst %,$(OPT.SYSINCLUDE)%,$(SYSTEMINCLUDE))
-PINCLUDE:=$(OPT.PREINCLUDE)$(PRODUCT_INCLUDE)
-INCLUDES:=$(UINCLUDE) $(OPT.SPLITINCLUDE) $(SINCLUDE) $(PINCLUDE)
-
-DEFINES:=$(call makemacrodef,$(OPT.DEFINE),$(CDEFS) $(TARGET_MACRO))
-
-
-# .mmp XML description file
-ifneq ($(PROCESSED_$(call sanitise,$(MMPXMLFILE))),1)
-
-  ifeq ($(LINKAS),)
-    LINKASBASE:=$(TARGET).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(TARGETTYPE))
-  else
-    LINKASBASE:=$(LINKAS)
-  endif
-
-  LINKASVERSIONED:=$(basename $(LINKASBASE)){$(VERSIONHEX)}$(suffix $(LINKASBASE))
-
-  ADDED_CAPABILITIES:=$(subst $(CHAR_SPACE),+,$(filter-out -%,$(CAPABILITY)))
-  SUBTRACTED_CAPABILITIES:=$(subst $(CHAR_SPACE),,$(filter -%,$(CAPABILITY)))
-  FINAL_CAPABILITIES:=$(if $(ADDED_CAPABILITIES),$(ADDED_CAPABILITIES)$(SUBTRACTED_CAPABILITIES),none)
-
-  ifeq ($(UID2),00000000)
-    UID2:=$(if $(UID2_ZERO_OVERRIDE),$(UID2_ZERO_OVERRIDE),00000000)
-  endif
-
-  define gccxmlmeta2xml
-  # note: we jump through some rather awkward hoops here in an attempt to not cause issues for the Bash shell
-  # with gargantuan concatenated "echo" statements.  This includes not being wrapped by start/endrule and
-  # using grouping functions where appropriate.
-    $(1):
-	  $(call startrule,gccxmlmeta2xml) \
-	    echo creating $(1) quietly \
-	  $(call endrule,gccxmlmeta2xml)
-	  @echo -e \
-	    "<?xml version=\"1.0\"?>\n" \
-	    "<mmpInfo>\n" \
-	    "\t<mmp path=\"$(PROJECT_META)\"/>\n" \
-	    "\t<target name=\"$(TARGET).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(TARGETTYPE))\" type=\"$(TARGETTYPE)\"$(if $(TARGETPATH), path=\"$(TARGETPATH)\",)/>\n" \
-	    "\t<cwd path=\"$(dir $(COMPONENT_META))\"/>\n" \
-	    "\t<abi type=\"ARM4\"/>\n" \
-	    "\t<linkAs name=\"$(LINKASVERSIONED)\"/>\n" \
-	    "\t<linkAsBase name=\"$(LINKASBASE)\"/>\n" \
-	    "\t<uids$(if $(UID1), u0=\"0x$(UID1)\",)$(if $(UID2), u1=\"0x$(UID2)\",)$(if $(UID3), u2=\"0x$(UID3)\",)/>\n" \
-	    "\t<version major=\"$(basename $(VERSION))\" minor=\"$(subst .,,$(suffix $(VERSION)))\"/>\n" \
-	    "\t<capability id=\"$(FINAL_CAPABILITIES)\"/>\n" \
-	    "\t<defFile path=\"\" type=\"GCC\"/>\n" \
-	    "\t<defFile path=\"$(DEFFILE)\" type=\"EABI\"/>\n" \
-	    "\t<libs>\n" \
-	    "\t\t<lib name=\"$(FIRSTLIB)\" type=\"First\"/>" \
-	    > $(1)
-	  $(call groupreplacein50infile,\t\t<lib name=\"__VERBATIM__\"/>,$(subst .dso,.lib,$(LIBRARY)),$(1))
-	  $(call groupreplacein50infile,\t\t<lib name=\"__VERBATIM__\"/>,$(STATICLIBRARY),$(1))
-	  @echo -e \
-	    "\t</libs>\n" \
-	    "\t<resources>" \
-	    >> $(1)
-	  $(call groupreplacein50infile,\t\t<resource name=\"__FILENAME__\"/>,$(RFIFILES),$(1))
-	  @echo -e \
-	    "\t</resources>" \
-	    >> $(1)
-	  $(call groupreplacein50infile,\t<sourceFile name=\"__FILENAME__\" path=\"__PATH__\"/>,$(SOURCE),$(1))
-	  $(call groupreplacein50infile,\t<export name=\"__VERBATIM__\"/>,$(EXPORTHEADERS),$(1))
-	  @echo -e \
-	    "</mmpInfo>\n" \
-	    >> $(1)
-  endef
-
-  $(eval $(call gccxmlmeta2xml,$(MMPXMLFILE)))
-  $(eval PROCESSED_$(call sanitise,$(MMPXMLFILE)):=1)
-endif
-
-
-# process straight source files into .xml files, generating .d dependency files and updating includeheaders.txt
-# note: includeheaders.txt is neither tracked as a formal dependency, nor deleted during a clean.  This mirrors
-# the situation with ABLD where the GCCXML build continually updates the file as it finds it.
-define gccxmlprocesssource
-
-  $(eval DEPENDFILENAME:=$(call mapsource2output,$(1),.xml.d))
-  $(eval DEPENDFILE:=$(DEPENDFILENAME))
-
-  $(call mapsource2output,$(1),.xml): $(1) $(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT)
-	$(call startrule,gccxmlprocesssource) \
-	$(CC) $(CFLAGS) $(OPTION_GCCXML) \
-	$(if $(filter $(CIAFILEEXTENSIONS),$(1)),$(call makemacrodef,$(OPT.DEFINE),__CIA__),) \
-	$(DEFINES) \
-	$(OPT.USERINCLUDE)$(patsubst %/,%,$(dir $(1))) \
-	$(INCLUDES) \
-	-fxml="$$@" -MD "$$@.d" -MT "$$@" $(OPT.OUT) nul "$(1)" && \
-	$(GNUSED) '/^.*\.xml:.*$$$$/d;/^ [a-zA-Z].*$$$$/d;s/^  //;s/ \\\$$$$//;s/\/\//\//g;/^s*$$$$/d' < $$@.d | $(GNUAWK) '{sub(/ /,"\n")};1' >> $(INCLUDESFILE) \
-	$(call endrule,gccxmlprocesssource)
-
-    CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
-    ifneq "$(DEPENDFILE)" ""
-    ifeq ($(NO_DEPEND_INCLUDE),)
-      ifeq "$(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS)))" ""
-        -include $(DEPENDFILE)
-      endif
-    endif
-    endif
-
-endef
-$(foreach SRCFILE,$(SOURCE),$(eval $(call gccxmlprocesssource,$(SRCFILE))))
-
-
-# package output
-# this is done in a slightly indirect way in order to work around the fact that the ABLD GCCXML build doesn't always pick
-# a unique name for .gxp files for some components with multiple .mmp files i.e. it deletes/generates the same name
-# .gxp file over, and over, again.  What follows ensures that the build tree .gxp file is always unique, and that
-# we just publish that last one that is built.  This mirrors what ABLD achieves, and avoids "overriding" warnings in
-# makefile processing.
-# note: the main call here needs to reside outside of start/endrule in order to avoid command line length issues.
-define gccxmlpackage
-  $(TEMPGXPARCHIVE): $(MMPXMLFILE) $(SRCXMLFILES) $(DEFFILE)
-	  $$(call groupcallin50,$(ZIP) -j $$@,$$^ $(RFIFILES)) ;
-	  $(call startrule,gccxmlpackage) \
-	  $(GNURM) -f $(GXPARCHIVE) && \
-	  $(GNUCP) $$@ $(GXPARCHIVE) \
-	  $(if $(SAVESPACE),; $(GNURM) -rf $(VARIANTBLDPATH); true,) \
-	  $(call endrule,gccxmlpackage)
-
-  $(GXPARCHIVE): $(TEMPGXPARCHIVE)
-endef
-$(eval $(gccxmlpackage))
-
-# Global targets
-.PHONY:: $(ALLTARGET)
-$(ALLTARGET):: $(RELEASABLES)
-TARGET:: $(RELEASABLES)
-
-# clean up
-$(eval $(call GenerateStandardCleanTarget,$(CLEANTARGETS),$(CREATABLEPATHS),))
-$(call makepath, $(CREATABLEPATHS))
-
+# Copyright (c) 2008-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:
+# All targets Function Like Makefile (FLM) supporting the execution of
+# gccxml_cc1plus on source, the creation of project and resource descriptive XML files
+# and packaging into an appropriate archive for CDB processing.
+#
+#
+
+
+# passed in values, stripped of whitespace
+DEFFILE:=$(strip $(DEFFILE))
+LINKAS:=$(strip $(LINKAS))
+UID1:=$(strip $(UID1))
+UID2:=$(strip $(UID2))
+UID3:=$(strip $(UID3))
+
+# local variables
+CREATABLEPATHS:=
+CLEANTARGETS:=
+RELEASABLES:=
+STDCPP_BUILD:=
+CIAFILEEXTENSIONS:=%.CIA %.cia %.Cia %.cIa %.cIA %.ciA %.CIa %.CiA
+
+ROOTBLDPATH:=$(OUTPUTPATH)/gccxml
+VARIANTBLDPATH:=$(OUTPUTPATH)/$(FULLVARIANTPATH)
+ROOTRELEASEPATH:=$(RELEASEPATH)/gccxml
+VARIANTRELEASEPATH:=$(RELEASEPATH)/$(FULLVARIANTPATH)
+
+CREATABLEPATHS:=$(CREATABLEPATHS) $(VARIANTBLDPATH) $(VARIANTRELEASEPATH) $(ROOTBLDPATH) $(ROOTRELEASEPATH)
+
+# type-specific definitions
+BASE_TYPE:=dll
+TARGET_MACRO:=__DLL__
+ifneq ($(findstring exe,$(TARGETTYPE)),)
+  BASE_TYPE:=exe
+  TARGET_MACRO:=__EXE__
+endif
+ifneq ($(findstring lib,$(TARGETTYPE)),)
+  BASE_TYPE:=lib
+  TARGET_MACRO:=
+endif
+
+# utility functions
+# returns absolutely-pathed temporary build filenames based solely on the basename of the source file, but with an additional "_" for .cia files
+# $(1) input source file list
+# $(2) output file extension
+define mapsource2output
+  $(foreach SOURCEFILE,$(1),$(patsubst %, $(VARIANTBLDPATH)/%, $(basename $(notdir $(SOURCEFILE)))$(if $(filter $(CIAFILEEXTENSIONS),$(SOURCEFILE)),_,)$(2)))
+endef
+
+# returns absolutely-pathed temporary build filenames based on the full resource filename
+# $(1) input resource file list
+# $(2) output file extension
+define mapresource2output
+  $(patsubst %, $(ROOTBLDPATH)/%, $(addsuffix $(2),$(notdir $(1))))
+endef
+
+# calls a tool multiple times with grouped arguments
+# $(1) tool to call with any non-variable arguments
+# $(2) list of further variable arguments to group in 150 element calls
+define groupcallin50
+	$(if $2,$1 $(foreach L,$(wordlist 1,50,$2),$(L)),)
+	$(if $2,$(call groupcallin50,$1,$(wordlist 51,$(words $2),$2)),@true)
+endef
+
+# echos content to a file in groups performing optional search/replace based on passed args
+# $(1) template line with optional __VERBATIM__, __PATH__, __FILENAME__ replacements
+# $(2) list of pathed filenames to be batch processed and that can be used for template replacements
+# $(3) output file
+define groupreplacein50infile
+	$(if $2,@echo -e $(foreach L,$(wordlist 1,50,$2),"$(subst __VERBATIM__,$(L),$(subst __PATH__,$(dir $(L)),$(subst __FILENAME__,$(notdir $(L)),$1)))\\n") >>$3,)
+	$(if $2,$(call groupreplacein50infile,$1,$(wordlist 51,$(words $2),$2),$3),@true)
+endef
+
+# targets
+INCLUDESFILE:=$(ROOTRELEASEPATH)/includeheaders.txt
+MMPXMLFILE:=$(ROOTBLDPATH)/$(notdir $(PROJECT_META)).xml
+SRCXMLFILES:=$(call mapsource2output,$(SOURCE),.xml)
+RFIFILES:=$(call mapresource2output,$(RESOURCEFILES),.rfi)
+DEPFILES:=$(call mapsource2output,$(SOURCE),.xml.d)
+TEMPGXPARCHIVE:=$(VARIANTBLDPATH)/$(TARGET)$(BASE_TYPE).gxp
+GXPARCHIVE:=$(VARIANTRELEASEPATH)/$(TARGET)$(BASE_TYPE).gxp
+
+CLEANTARGETS:=$(CLEANTARGETS) $(MMPXMLFILE) $(SRCXMLFILES) $(DEPFILES) $(TEMPGXPARCHIVE)
+RELEASABLES:=$(RELEASABLES) $(GXPARCHIVE)
+
+# Deduce whether we should be performing a build with standard CPP characteristics
+# This operates differently per-OS release, although OE TARGETTYPEs always build with standard CPP traits
+ifeq ($(OPEN_ENVIRONMENT),1)
+  STDCPP_BUILD:=1
+endif
+
+ifeq ($(SUPPORTS_STDCPP_NEWLIB),1)
+  ifeq ($(NOSTDCPP),1)
+    STDCPP_BUILD:=
+  else
+    ifeq ($(STDCPP),1)
+      STDCPP_BUILD:=1
+    endif
+  endif
+endif
+
+ifeq ($(STDCPP_BUILD),1)
+  CDEFS:=$(CDEFS) $(STDCPP_DEF)
+  SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(STDCPP_INCLUDE)
+endif
+
+CDEFS:=$(CDEFS) $(TARGET_DEFS)
+SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(TARGET_INCLUDES)
+
+# include paths
+UINCLUDE:=$(patsubst %,$(OPT.USERINCLUDE)%,$(USERINCLUDE))
+SINCLUDE:=$(patsubst %,$(OPT.SYSINCLUDE)%,$(SYSTEMINCLUDE))
+PINCLUDE:=$(OPT.PREINCLUDE)$(PRODUCT_INCLUDE)
+INCLUDES:=$(UINCLUDE) $(OPT.SPLITINCLUDE) $(SINCLUDE) $(PINCLUDE)
+
+DEFINES:=$(call makemacrodef,$(OPT.DEFINE),$(CDEFS) $(TARGET_MACRO))
+
+
+# .mmp XML description file
+ifneq ($(PROCESSED_$(call sanitise,$(MMPXMLFILE))),1)
+
+  ifeq ($(LINKAS),)
+    LINKASBASE:=$(TARGET).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(TARGETTYPE))
+  else
+    LINKASBASE:=$(LINKAS)
+  endif
+
+  LINKASVERSIONED:=$(basename $(LINKASBASE)){$(VERSIONHEX)}$(suffix $(LINKASBASE))
+
+  ADDED_CAPABILITIES:=$(subst $(CHAR_SPACE),+,$(filter-out -%,$(CAPABILITY)))
+  SUBTRACTED_CAPABILITIES:=$(subst $(CHAR_SPACE),,$(filter -%,$(CAPABILITY)))
+  FINAL_CAPABILITIES:=$(if $(ADDED_CAPABILITIES),$(ADDED_CAPABILITIES)$(SUBTRACTED_CAPABILITIES),none)
+
+  ifeq ($(UID2),00000000)
+    UID2:=$(if $(UID2_ZERO_OVERRIDE),$(UID2_ZERO_OVERRIDE),00000000)
+  endif
+
+  define gccxmlmeta2xml
+  # note: we jump through some rather awkward hoops here in an attempt to not cause issues for the Bash shell
+  # with gargantuan concatenated "echo" statements.  This includes not being wrapped by start/endrule and
+  # using grouping functions where appropriate.
+    $(1):
+	  $(call startrule,gccxmlmeta2xml) \
+	    echo creating $(1) quietly \
+	  $(call endrule,gccxmlmeta2xml)
+	  @echo -e \
+	    "<?xml version=\"1.0\"?>\n" \
+	    "<mmpInfo>\n" \
+	    "\t<mmp path=\"$(PROJECT_META)\"/>\n" \
+	    "\t<target name=\"$(TARGET).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(TARGETTYPE))\" type=\"$(TARGETTYPE)\"$(if $(TARGETPATH), path=\"$(TARGETPATH)\",)/>\n" \
+	    "\t<cwd path=\"$(dir $(COMPONENT_META))\"/>\n" \
+	    "\t<abi type=\"ARM4\"/>\n" \
+	    "\t<linkAs name=\"$(LINKASVERSIONED)\"/>\n" \
+	    "\t<linkAsBase name=\"$(LINKASBASE)\"/>\n" \
+	    "\t<uids$(if $(UID1), u0=\"0x$(UID1)\",)$(if $(UID2), u1=\"0x$(UID2)\",)$(if $(UID3), u2=\"0x$(UID3)\",)/>\n" \
+	    "\t<version major=\"$(basename $(VERSION))\" minor=\"$(subst .,,$(suffix $(VERSION)))\"/>\n" \
+	    "\t<capability id=\"$(FINAL_CAPABILITIES)\"/>\n" \
+	    "\t<defFile path=\"\" type=\"GCC\"/>\n" \
+	    "\t<defFile path=\"$(DEFFILE)\" type=\"EABI\"/>\n" \
+	    "\t<libs>\n" \
+	    "\t\t<lib name=\"$(FIRSTLIB)\" type=\"First\"/>" \
+	    > $(1)
+	  $(call groupreplacein50infile,\t\t<lib name=\"__VERBATIM__\"/>,$(subst .dso,.lib,$(LIBRARY)),$(1))
+	  $(call groupreplacein50infile,\t\t<lib name=\"__VERBATIM__\"/>,$(STATICLIBRARY),$(1))
+	  @echo -e \
+	    "\t</libs>\n" \
+	    "\t<resources>" \
+	    >> $(1)
+	  $(call groupreplacein50infile,\t\t<resource name=\"__FILENAME__\"/>,$(RFIFILES),$(1))
+	  @echo -e \
+	    "\t</resources>" \
+	    >> $(1)
+	  $(call groupreplacein50infile,\t<sourceFile name=\"__FILENAME__\" path=\"__PATH__\"/>,$(SOURCE),$(1))
+	  $(call groupreplacein50infile,\t<export name=\"__VERBATIM__\"/>,$(EXPORTHEADERS),$(1))
+	  @echo -e \
+	    "</mmpInfo>\n" \
+	    >> $(1)
+  endef
+
+  $(eval $(call gccxmlmeta2xml,$(MMPXMLFILE)))
+  $(eval PROCESSED_$(call sanitise,$(MMPXMLFILE)):=1)
+endif
+
+
+# process straight source files into .xml files, generating .d dependency files and updating includeheaders.txt
+# note: includeheaders.txt is neither tracked as a formal dependency, nor deleted during a clean.  This mirrors
+# the situation with ABLD where the GCCXML build continually updates the file as it finds it.
+define gccxmlprocesssource
+
+  $(eval DEPENDFILENAME:=$(call mapsource2output,$(1),.xml.d))
+  $(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
+
+  $(call mapsource2output,$(1),.xml): $(1) $(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT)
+	$(call startrule,gccxmlprocesssource) \
+	$(CC) $(CFLAGS) $(OPTION_GCCXML) \
+	$(if $(filter $(CIAFILEEXTENSIONS),$(1)),$(call makemacrodef,$(OPT.DEFINE),__CIA__),) \
+	$(DEFINES) \
+	$(OPT.USERINCLUDE)$(patsubst %/,%,$(dir $(1))) \
+	$(INCLUDES) \
+	-fxml="$$@" -MD "$$@.d" -MT "$$@" $(OPT.OUT) nul "$(1)" && \
+	$(GNUSED) '/^.*\.xml:.*$$$$/d;/^ [a-zA-Z].*$$$$/d;s/^  //;s/ \\\$$$$//;s/\/\//\//g;/^s*$$$$/d' < $$@.d | $(GNUAWK) '{sub(/ /,"\n")};1' >> $(INCLUDESFILE) \
+	$(call endrule,gccxmlprocesssource)
+
+    CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
+    ifneq ($(DEPENDFILE),)
+      ifeq ($(NO_DEPEND_INCLUDE),)
+        ifeq ($(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS))),)
+          -include $(DEPENDFILE)
+        endif
+      endif
+    endif
+
+endef
+$(foreach SRCFILE,$(SOURCE),$(eval $(call gccxmlprocesssource,$(SRCFILE))))
+
+
+# package output
+# this is done in a slightly indirect way in order to work around the fact that the ABLD GCCXML build doesn't always pick
+# a unique name for .gxp files for some components with multiple .mmp files i.e. it deletes/generates the same name
+# .gxp file over, and over, again.  What follows ensures that the build tree .gxp file is always unique, and that
+# we just publish that last one that is built.  This mirrors what ABLD achieves, and avoids "overriding" warnings in
+# makefile processing.
+# note: the main call here needs to reside outside of start/endrule in order to avoid command line length issues.
+define gccxmlpackage
+  $(TEMPGXPARCHIVE): $(MMPXMLFILE) $(SRCXMLFILES) $(DEFFILE)
+	  $$(call groupcallin50,@$(ZIP) -j $$@ > /dev/null 2>&1,$$^ $(RFIFILES)) ;
+	  $(call startrule,gccxmlpackage) \
+	  $(GNURM) -f $(GXPARCHIVE) && \
+	  $(GNUCP) $$@ $(GXPARCHIVE) \
+	  $(if $(SAVESPACE),; $(GNURM) -rf $(VARIANTBLDPATH); true,) \
+	  $(call endrule,gccxmlpackage)
+
+  $(GXPARCHIVE): $(TEMPGXPARCHIVE)
+endef
+$(eval $(gccxmlpackage))
+
+# Global targets
+.PHONY:: $(ALLTARGET)
+$(ALLTARGET):: $(RELEASABLES)
+TARGET:: $(RELEASABLES)
+
+# clean up
+$(call raptor_clean,$(CLEANTARGETS))
+$(call makepath, $(CREATABLEPATHS))
+
--- a/sbsv2/raptor/lib/flm/gccxmlresource.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/gccxmlresource.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,37 +1,37 @@
-# 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:
-# Thin Function Like Makefile (FLM) wrapper to general resource building FLM
-# for gccxml builds.
-# 
-#
-
-
-# .rfi files need to be generated to a known location that is determined by the "core" GCCXML wrapper build
-RFIFILE:=$(MAIN_OUTPUTPATH)/$(OUTPUTPATHOFFSET)/$(MAIN_TARGET_lower)_$(MAIN_REQUESTEDTARGETEXT)/gccxml/$(notdir $(SOURCE)).rfi
-
-define generaterfifile
-# $(1) is the .rfi filename
-# $(2) is the list of .rpp files
-# $(3) is the list of dependency files
-
-   $(1): $(2)
-	$(call startrule,generaterfifile,FORCESUCCESS) \
-	$(CREATERFIFILE) -o $(1) -x "$(EPOCROOT)/epoc32" $(3) \
-	$(call endrule,generaterfifile)
-endef
-
-# Main (and mostly generic) resource building FLM
-include $(FLMHOME)/resource.flm
-
-
+# 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:
+# Thin Function Like Makefile (FLM) wrapper to general resource building FLM
+# for gccxml builds.
+# 
+#
+
+
+# .rfi files need to be generated to a known location that is determined by the "core" GCCXML wrapper build
+RFIFILE:=$(MAIN_OUTPUTPATH)/$(OUTPUTPATHOFFSET)/$(MAIN_TARGET_lower)_$(MAIN_REQUESTEDTARGETEXT)/gccxml/$(notdir $(SOURCE)).rfi
+
+define generaterfifile
+# $(1) is the .rfi filename
+# $(2) is the list of .rpp files
+# $(3) is the list of dependency files
+
+   $(1): $(2)
+	$(call startrule,generaterfifile,FORCESUCCESS) \
+	$(CREATERFIFILE) -o $(1) -x "$(EPOCROOT)/epoc32" $(3) \
+	$(call endrule,generaterfifile)
+endef
+
+# Main (and mostly generic) resource building FLM
+include $(FLMHOME)/resource.flm
+
+
--- a/sbsv2/raptor/lib/flm/globals.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/globals.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,158 +1,158 @@
-#
-# 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: 
-# global include file : this is included by all generated makefiles
-# 1) include all the common tools
-# 2) add global targets such as CLEAN and REALLYCLEAN
-# 3) specify the top level dependencies between targets
-# INPUTS : assumes OSTYPE and FLMHOME are set.
-#
-
-ifeq ($(SYMBIAN_FLM_GLOBALS_MK),)
-SYMBIAN_FLM_GLOBALS_MK:=1
-
-# get the common tools
-include $(FLMHOME)/flmtools.mk
-
-# initialise the list of created directories
-makepathLIST:=
-
-# set the variables TOOLPLATFORMDIR and DOTEXE
-ifeq ($(filter win,$(HOSTPLATFORM)),win)
-DOTEXE:=.exe
-TOOLPLATFORMDIR:=
-else
-DOTEXE:=
-TOOLPLATFORMDIR:=/$(HOSTPLATFORM_DIR)
-endif
-
-# addglobal(GlobalTargetName)
-SYMBIAN_GLOBAL_TARGETS:=
-
-define sgt_addcmds
-.PHONY:: $1
-
-$(if $(filter win,$(HOSTPLATFORM)),,$(call lowercase,$1):: $1)
-
-SYMBIAN_GLOBAL_TARGETS:=$$(SYMBIAN_GLOBAL_TARGETS) $(1)
-endef
-
-define addglobal
-$(eval $(call sgt_addcmds,$(1)))
-endef
-
-ALLTARGET:=ALL
-
-.PHONY:: $(ALLTARGET)
-$(ALLTARGET):: BUILD
-
-# Global targets should generally be double colon rules because
-# they allow horizontal states to be placed into the build system.
-# e.g the "EXPORTED" state.
-$(call addglobal,BUILD)
-$(call addglobal,CLEAN)
-$(call addglobal,CLEANEXPORT)
-$(call addglobal,EXPORT)
-$(call addglobal,FINAL)
-$(call addglobal,FREEZE)
-$(call addglobal,LIBRARY)
-$(call addglobal,LISTING)
-$(call addglobal,MAKEFILE)
-$(call addglobal,REALLYCLEAN)
-$(call addglobal,BITMAP)
-$(call addglobal,RESOURCE)
-$(call addglobal,ROMFILE)
-$(call addglobal,TARGET)
-$(call addglobal,WHAT)
-$(call addglobal,WHATEXPORTS)
-$(call addglobal,WHATARMV5)
-$(call addglobal,WHATWINSCW)
-$(call addglobal,WHATTOOLS2)
-$(call addglobal,WHATTOOLS)
-$(call addglobal,WHATTEM)
-$(call addglobal,WHATRESOURCES)
-$(call addglobal,WHATBITMAP)
-$(call addglobal,WHATGNUEM)
-$(call addglobal,WHATSTRINGTABLE)
-
-# Ignore errors in some rules so as to "keep going"
-# so if one export fails then that won't stop unrelated
-# .cpp files from building. (.cpp files must all depend on EXPORT
-# so that parallel builds work)
-.IGNORE: EXPORT BITMAP RESOURCE LIBRARY
-# dependencies between top-level targets
-BUILD:: EXPORT MAKEFILE BITMAP RESOURCE LIBRARY TARGET FINAL
-
-MAKEFILE:: EXPORT
-BITMAP:: MAKEFILE
-RESOURCE:: BITMAP
-LIBRARY:: RESOURCE 
-TARGET:: LIBRARY
-FINAL:: TARGET
-
-.PHONY:: EXPORT
-
-
-WHAT:: WHATEXPORTS WHATARMV5 WHATWINSCW WHATTOOLS2 WHATTEM WHATGNUEM WHATRESOURCES WHATBITMAP WHATSTRINGTABLE
-
-REALLYCLEAN:: CLEAN CLEANEXPORT
-
-# Create one of every double colon rule
-WHATBITMAP::
-
-WHATRESOURCES::
-
-WHATSTRINGTABLE::
-
-WHATTEM::
-
-WHATGNUEM::
-
-WHATTOOLS2::
-
-WHATWINSCW::
-
-WHATARMV5::
-
-WHATEXPORTS::
-
-LISTING::
-
-CLEAN::
-
-CLEANEXPORT::
-
-REALLYCLEAN::
-
-EXPORT::
-
-RESOURCE::
-
-BITMAP::
-
-# put known resource header to resource header dependencies here
-
-eikcdlg_DEPENDS:=eikcore.rsg eikcoctl.rsg
-eikmisc_DEPENDS:=eikcore.rsg
-eikfile_DEPENDS:=eikcoctl.rsg
-eikir_DEPENDS:=eikcoctl.rsg
-eikprint_DEPENDS:=eikcoctl.rsg
-
-
-# For users of SBSv2 who wish to add in their own global settings
-# without modifying this file:
--include $(FLMHOME)/user/globals.mk
-
-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: 
+# global include file : this is included by all generated makefiles
+# 1) include all the common tools
+# 2) add global targets such as CLEAN and REALLYCLEAN
+# 3) specify the top level dependencies between targets
+# INPUTS : assumes OSTYPE and FLMHOME are set.
+#
+
+ifeq ($(SYMBIAN_FLM_GLOBALS_MK),)
+SYMBIAN_FLM_GLOBALS_MK:=1
+
+# get the common tools
+include $(FLMHOME)/flmtools.mk
+
+# initialise the list of created directories
+makepathLIST:=
+
+# set the variables TOOLPLATFORMDIR and DOTEXE
+ifeq ($(filter win,$(HOSTPLATFORM)),win)
+DOTEXE:=.exe
+TOOLPLATFORMDIR:=
+else
+DOTEXE:=
+TOOLPLATFORMDIR:=/$(HOSTPLATFORM_DIR)
+endif
+
+# addglobal(GlobalTargetName)
+SYMBIAN_GLOBAL_TARGETS:=
+
+define sgt_addcmds
+.PHONY:: $1
+
+$(if $(filter win,$(HOSTPLATFORM)),,$(call lowercase,$1):: $1)
+
+SYMBIAN_GLOBAL_TARGETS:=$$(SYMBIAN_GLOBAL_TARGETS) $(1)
+endef
+
+define addglobal
+$(eval $(call sgt_addcmds,$(1)))
+endef
+
+ALLTARGET:=ALL
+
+.PHONY:: $(ALLTARGET)
+$(ALLTARGET):: BUILD
+
+# Global targets should generally be double colon rules because
+# they allow horizontal states to be placed into the build system.
+# e.g the "EXPORTED" state.
+$(call addglobal,BUILD)
+$(call addglobal,CLEAN)
+$(call addglobal,CLEANEXPORT)
+$(call addglobal,EXPORT)
+$(call addglobal,FINAL)
+$(call addglobal,FREEZE)
+$(call addglobal,LIBRARY)
+$(call addglobal,LISTING)
+$(call addglobal,MAKEFILE)
+$(call addglobal,REALLYCLEAN)
+$(call addglobal,BITMAP)
+$(call addglobal,RESOURCE)
+$(call addglobal,ROMFILE)
+$(call addglobal,TARGET)
+$(call addglobal,WHAT)
+$(call addglobal,WHATEXPORTS)
+$(call addglobal,WHATARMV5)
+$(call addglobal,WHATWINSCW)
+$(call addglobal,WHATTOOLS2)
+$(call addglobal,WHATTOOLS)
+$(call addglobal,WHATTEM)
+$(call addglobal,WHATRESOURCES)
+$(call addglobal,WHATBITMAP)
+$(call addglobal,WHATGNUEM)
+$(call addglobal,WHATSTRINGTABLE)
+
+# Ignore errors in some rules so as to "keep going"
+# so if one export fails then that won't stop unrelated
+# .cpp files from building. (.cpp files must all depend on EXPORT
+# so that parallel builds work)
+.IGNORE: EXPORT BITMAP RESOURCE LIBRARY
+# dependencies between top-level targets
+BUILD:: EXPORT MAKEFILE BITMAP RESOURCE LIBRARY TARGET FINAL
+
+MAKEFILE:: EXPORT
+BITMAP:: MAKEFILE
+RESOURCE:: BITMAP
+LIBRARY:: RESOURCE 
+TARGET:: LIBRARY
+FINAL:: TARGET
+
+.PHONY:: EXPORT
+
+
+WHAT:: WHATEXPORTS WHATARMV5 WHATWINSCW WHATTOOLS2 WHATTEM WHATGNUEM WHATRESOURCES WHATBITMAP WHATSTRINGTABLE
+
+REALLYCLEAN:: CLEAN CLEANEXPORT
+
+# Create one of every double colon rule
+WHATBITMAP::
+
+WHATRESOURCES::
+
+WHATSTRINGTABLE::
+
+WHATTEM::
+
+WHATGNUEM::
+
+WHATTOOLS2::
+
+WHATWINSCW::
+
+WHATARMV5::
+
+WHATEXPORTS::
+
+LISTING::
+
+CLEAN::
+
+CLEANEXPORT::
+
+REALLYCLEAN::
+
+EXPORT::
+
+RESOURCE::
+
+BITMAP::
+
+# put known resource header to resource header dependencies here
+
+eikcdlg_DEPENDS:=eikcore.rsg eikcoctl.rsg
+eikmisc_DEPENDS:=eikcore.rsg
+eikfile_DEPENDS:=eikcoctl.rsg
+eikir_DEPENDS:=eikcoctl.rsg
+eikprint_DEPENDS:=eikcoctl.rsg
+
+
+# For users of SBSv2 who wish to add in their own global settings
+# without modifying this file:
+-include $(FLMHOME)/user/globals.mk
+
+endif
+
--- a/sbsv2/raptor/lib/flm/gnumakefile.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/gnumakefile.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,191 +1,191 @@
-# 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:
-# Gnumakefile FLM -> Knows how to run gnumakefiles
-# Will only work on Windows
-# 
-#
-
-TMPROOT:=$(subst \,/,$(EPOCROOT))
-OLD_EPOCROOT:=$(patsubst %/,%,$(TMPROOT))/
-OLDSTYLE_EPOCROOT:=$(subst /,\,$(OLD_EPOCROOT))
-
-# Set up the correct make to be invoked
-MAKEVAR:=
-ifeq ($(USENMAKE),1)
-MAKEVAR:=$(NMAKE) $(NMAKEFLAGS)
-else
-MAKEVAR:="$(SBSV1MAKE)"
-endif
-
-################################# FLM Parameter description ##
-# Parameters:
-#   EPOCROOT:=
-#   PLATFORM:=$(VARIANTPLATFORM)
-# The current configuration either UREL or UDEB:
-#   CFG:=$(VARIANTTYPE)
-# Relative path to EPOCROOT. (to where?):
-#   TO_ROOT:=
-# The path to the top-level bld.inf.
-# Note: if a bld.inf file #includes another bld.inf, this variable will
-# always contain the directory of that top-level file. If you require
-# the directory of the bld.inf which actually references the makefile,
-# use $(EXTENSION_ROOT) instead.
-#   TO_BLDINF:=
-# The project's working build directory under \epoc32\build\..
-#   EPOCBLD:=
-
-
-################################ Standard Variables ##
-# We may set the following 
-# for the sake of gnumakefiles which
-# need to know them:
-
-## Path element separator.
-/:=/
-## PATH environment variable separator.
-;:=:
-
-####
-# Various file and directory manipulation tools.
-# We are using the standard GNU coretools.
-# On Windows these are supplied by CYGWIN
-RMDIR:=$(GNURMDIR)
-RM:=$(GNURM)
-ERASE:=$(GNURM)
-MKDIR:=$(GNUMKDIR)
-CP:=$(GNUCP)
-
-# Targets:
-# We need to hook the BLD, LIB, ..., targets in the gnumakefile into the
-# global phony TARGET, LIBRARY, ..., targets in the overall Makefile.
-#
-# Additionally we need a specific name for each gnumakefile's targets so
-# that we can create dependencies between, say, the FINAL target of one
-# extension and the FINAL target of another. Ideally this name would be
-# unique but that would require the full path to be used so we compromise
-# and use a unique name and a portable reference that is relatively "unique".
-
-UNIQ:=$(DIRECTORY)$(EXTMAKEFILENAME)$(TO_ROOT)$(EPOCBLD)$(TO_BLDINF)$(PLATFORM)$(CFG)$(MAKEVAR)
-UNIQ:=$(word 1,$(shell echo $(UNIQ) | $(GNUMD5SUM)))
-gmake_$(notdir $(EXTMAKEFILENAME))_$(PLATFORM)_$(CFG):=$(UNIQ)
-CFG_uppercase:=$(call uppercase,$(CFG))
-
-RVCT22BIN:=$(RVCTBIN)
-RVCT22LIB:=$(RVCTLIB)
-RVCT22INC:=$(RVCTINC)
-
-EXTMAKEFILEPARAMETERS:= \
-	EPOCROOT PLATFORM TO_ROOT TO_BLDINF \
-	EPOCBLD CFG RMDIR RM ERASE MKDIR CP  \
-	MAKEFILENAME DIRECTORY EXTMAKEFILENAME            \
-	DEPENDENCIES TOOL RVCT22LIB RVCT22INC RVCT22BIN MAKEVAR
-
-# The standard gnumakefile Targets
-# These will be implemented in terms of double colon
-# rules - such that make FREEZE will cause all FREEZE 
-# targets to be evaluated.
-# For each call of this FLM we also need
-# to create unique versions of each of these targets
-# so that there is something to attach
-# the current FLM parameters to using target-specific 
-# variable declarations.
-
-EXTMAKETARGETS:= \
-	MAKMAKE     \
-	BLD         \
-	FREEZE      \
-	LIB         \
-	CLEANLIB    \
-	RESOURCE    \
-	CLEAN       \
-	RELEASABLES \
-	FINAL
-#	DO_NOTHING  
-
-# Hook into global targets
-#
-MAKEFILE::    $(UNIQ)_MAKMAKE
-BITMAP::      $(UNIQ)_MAKMAKE
-TARGET::      $(UNIQ)_BLD
-FREEZE::      $(UNIQ)_FREEZE
-LIBRARY::     $(UNIQ)_LIB
-CLEAN::       $(UNIQ)_CLEAN $(UNIQ)_CLEANLIB
-RESOURCE::    $(UNIQ)_RESOURCE
-FINAL::       $(UNIQ)_FINAL
-RELEASABLES:: $(UNIQ)_RELEASABLES
-
-# make sure gnumakefiles happen at the right stages
-MAKMAKE_DEPS:=EXPORT
-RESOURCE_DEPS:=BITMAP 
-LIB_DEPS:=RESOURCE
-BLD_DEPS:=LIBRARY
-FINAL_DEPS:=TARGET
-
-export /
-export ;
-
-#################################### Global Targets ##
-## All the global targets for the gnumakefiles
-# gnumakes are called as sub-makes, using make 3.79 from abld (passed through $(SBSV1MAKE)). 
-# makefile and nmakefile are called using nmake.
-
-define callgnumake
-.PHONY:: $(UNIQ)_$(1)
-
-$(EPOCROOT)/epoc32/build/TEM_$(1):: $(UNIQ)_$(1)
-
-$(UNIQ)_$(1): $($(1)_DEPS)
-	$(call startrule,extension_makefile,FORCESUCCESS) \
-	$(foreach V,$(EXTMAKEFILEPARAMETERS),$(V)='$($(V))') EXTMAKEFILETARGET='$(1)' \
-	$(if $(USENMAKE),export MAKEFLAGS="";cd "$(subst /,\,$(DIRECTORY))";,) export EPOCROOT="$(strip $(OLDSTYLE_EPOCROOT))\"; export CFG=$(CFG_uppercase); \
-	$(MAKEVAR) $(if $(USENMAKE),,-C "$(subst /,\,$(DIRECTORY))") -f "$(EXTMAKEFILENAME)" \
-	CFG=$(CFG_uppercase) EPOCBLD="$(subst /,\,$(EPOCBLD))" TO_BLDINF="$(subst /,\,$(TO_BLDINF))" PLATFORM=$(PLATFORM) $(if $(SAVESPACE),$(subst BLD,SAVESPACE,$(1)),$(1)) \
-	$(call endrule,extension_makefile) 
-ifneq ($(call isoneof,$(1),RELEASABLES FINAL),)
-	$(call startrawoutput) \
-	echo "$(call whatLogOpen)" ; \
-	$(foreach V,$(EXTMAKEFILEPARAMETERS),$(V)='$($(V))') EXTMAKEFILETARGET='RELEASABLES' \
-	$(if $(USENMAKE),export MAKEFLAGS="";cd "$(subst /,\,$(DIRECTORY))";,) export EPOCROOT="$(strip $(OLDSTYLE_EPOCROOT))\"; export CFG=$(CFG_uppercase); \
-	$(MAKEVAR) $(if $(USENMAKE),-C -S,-C "$(subst /,\,$(DIRECTORY))" --no-print-directory) -f "$(EXTMAKEFILENAME)" \
-	CFG=$(CFG_uppercase) EPOCBLD="$(subst /,\,$(EPOCBLD))" TO_BLDINF="$(subst /,\,$(TO_BLDINF))" PLATFORM=$(PLATFORM) RELEASABLES | \
-	(read -r LINE; while [ $$$$? -eq 0 ]; do \
-	if [[ ! $$$$LINE =~ "Nothing to be done for"  ]] ; then echo "$(call whatLogItem,EM,$$$$LINE)"; fi; \
-	read -r LINE; done; ); \
-	echo "$(call whatLogClose)" \
-	$(call endrawoutput)
-
-
-WHATGNUEM:: $(UNIQ)_RELEASABLES
-
-endif
-endef
-
-DO_NOTHING:: $(UNIQ)_DO_NOTHING 
-$(UNIQ)_DO_NOTHING: ;
-
-$(foreach EXTTRG,$(EXTMAKETARGETS),$(eval $(call callgnumake,$(EXTTRG))))
-
-## Do ROMFILE target in romstuff.mke
-ifeq ($(ROMFILE_$(call sanitise,$(EXTMAKEFILENAME))),)
-ROMFILE_$(call sanitise,$(EXTMAKEFILENAME)):=1
-
-ROMDIR:=$(subst $(OLD_EPOCROOT),$(OLD_EPOCROOT)epoc32/rom/,$(TO_BLDINF))
-
-define RomfileRomstuff
-ROMFILE::
-	@$(MAKEVAR) --no-print-directory $(if $(USENMAKE),,-C "$(subst /,\,$(DIRECTORY))") -f "$(EXTMAKEFILENAME)" ROMFILE >> $(ROMDIR)/ARMV5TEST.IBY
-endef
-
-$(eval $(call RomfileRomstuff))
-endif
+# 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:
+# Gnumakefile FLM -> Knows how to run gnumakefiles
+# Will only work on Windows
+# 
+#
+
+TMPROOT:=$(subst \,/,$(EPOCROOT))
+OLD_EPOCROOT:=$(patsubst %/,%,$(TMPROOT))/
+OLDSTYLE_EPOCROOT:=$(subst /,\,$(OLD_EPOCROOT))
+
+# Set up the correct make to be invoked
+MAKEVAR:=
+ifeq ($(USENMAKE),1)
+MAKEVAR:=$(NMAKE) $(NMAKEFLAGS)
+else
+MAKEVAR:="$(SBSV1MAKE)"
+endif
+
+################################# FLM Parameter description ##
+# Parameters:
+#   EPOCROOT:=
+#   PLATFORM:=$(VARIANTPLATFORM)
+# The current configuration either UREL or UDEB:
+#   CFG:=$(VARIANTTYPE)
+# Relative path to EPOCROOT. (to where?):
+#   TO_ROOT:=
+# The path to the top-level bld.inf.
+# Note: if a bld.inf file #includes another bld.inf, this variable will
+# always contain the directory of that top-level file. If you require
+# the directory of the bld.inf which actually references the makefile,
+# use $(EXTENSION_ROOT) instead.
+#   TO_BLDINF:=
+# The project's working build directory under \epoc32\build\..
+#   EPOCBLD:=
+
+
+################################ Standard Variables ##
+# We may set the following 
+# for the sake of gnumakefiles which
+# need to know them:
+
+## Path element separator.
+/:=/
+## PATH environment variable separator.
+;:=:
+
+####
+# Various file and directory manipulation tools.
+# We are using the standard GNU coretools.
+# On Windows these are supplied by CYGWIN
+RMDIR:=$(GNURMDIR)
+RM:=$(GNURM)
+ERASE:=$(GNURM)
+MKDIR:=$(GNUMKDIR)
+CP:=$(GNUCP)
+
+# Targets:
+# We need to hook the BLD, LIB, ..., targets in the gnumakefile into the
+# global phony TARGET, LIBRARY, ..., targets in the overall Makefile.
+#
+# Additionally we need a specific name for each gnumakefile's targets so
+# that we can create dependencies between, say, the FINAL target of one
+# extension and the FINAL target of another. Ideally this name would be
+# unique but that would require the full path to be used so we compromise
+# and use a unique name and a portable reference that is relatively "unique".
+
+UNIQ:=$(DIRECTORY)$(EXTMAKEFILENAME)$(TO_ROOT)$(EPOCBLD)$(TO_BLDINF)$(PLATFORM)$(CFG)$(MAKEVAR)
+UNIQ:=$(word 1,$(shell echo $(UNIQ) | $(GNUMD5SUM)))
+gmake_$(notdir $(EXTMAKEFILENAME))_$(PLATFORM)_$(CFG):=$(UNIQ)
+CFG_uppercase:=$(call uppercase,$(CFG))
+
+RVCT22BIN:=$(RVCTBIN)
+RVCT22LIB:=$(RVCTLIB)
+RVCT22INC:=$(RVCTINC)
+
+EXTMAKEFILEPARAMETERS:= \
+	EPOCROOT PLATFORM TO_ROOT TO_BLDINF \
+	EPOCBLD CFG RMDIR RM ERASE MKDIR CP  \
+	MAKEFILENAME DIRECTORY EXTMAKEFILENAME            \
+	DEPENDENCIES TOOL RVCT22LIB RVCT22INC RVCT22BIN MAKEVAR
+
+# The standard gnumakefile Targets
+# These will be implemented in terms of double colon
+# rules - such that make FREEZE will cause all FREEZE 
+# targets to be evaluated.
+# For each call of this FLM we also need
+# to create unique versions of each of these targets
+# so that there is something to attach
+# the current FLM parameters to using target-specific 
+# variable declarations.
+
+EXTMAKETARGETS:= \
+	MAKMAKE     \
+	BLD         \
+	FREEZE      \
+	LIB         \
+	CLEANLIB    \
+	RESOURCE    \
+	CLEAN       \
+	RELEASABLES \
+	FINAL
+#	DO_NOTHING  
+
+# Hook into global targets
+#
+MAKEFILE::    $(UNIQ)_MAKMAKE
+BITMAP::      $(UNIQ)_MAKMAKE
+TARGET::      $(UNIQ)_BLD
+FREEZE::      $(UNIQ)_FREEZE
+LIBRARY::     $(UNIQ)_LIB
+CLEAN::       $(UNIQ)_CLEAN $(UNIQ)_CLEANLIB
+RESOURCE::    $(UNIQ)_RESOURCE
+FINAL::       $(UNIQ)_FINAL
+RELEASABLES:: $(UNIQ)_RELEASABLES
+
+# make sure gnumakefiles happen at the right stages
+MAKMAKE_DEPS:=EXPORT
+RESOURCE_DEPS:=BITMAP 
+LIB_DEPS:=RESOURCE
+BLD_DEPS:=LIBRARY
+FINAL_DEPS:=TARGET
+
+export /
+export ;
+
+#################################### Global Targets ##
+## All the global targets for the gnumakefiles
+# gnumakes are called as sub-makes, using make 3.79 from abld (passed through $(SBSV1MAKE)). 
+# makefile and nmakefile are called using nmake.
+
+define callgnumake
+.PHONY:: $(UNIQ)_$(1)
+
+$(EPOCROOT)/epoc32/build/TEM_$(1):: $(UNIQ)_$(1)
+
+$(UNIQ)_$(1): $($(1)_DEPS)
+	$(call startrule,extension_makefile,FORCESUCCESS) \
+	$(foreach V,$(EXTMAKEFILEPARAMETERS),$(V)='$($(V))') EXTMAKEFILETARGET='$(1)' \
+	$(if $(USENMAKE),export MAKEFLAGS="";cd "$(subst /,\,$(DIRECTORY))";,) export EPOCROOT="$(strip $(OLDSTYLE_EPOCROOT))\"; export CFG=$(CFG_uppercase); \
+	$(MAKEVAR) $(if $(USENMAKE),,-C "$(subst /,\,$(DIRECTORY))") -f "$(EXTMAKEFILENAME)" \
+	CFG=$(CFG_uppercase) EPOCBLD="$(subst /,\,$(EPOCBLD))" TO_BLDINF="$(subst /,\,$(TO_BLDINF))" PLATFORM=$(PLATFORM) $(if $(SAVESPACE),$(subst BLD,SAVESPACE,$(1)),$(1)) \
+	$(call endrule,extension_makefile) 
+ifneq ($(call isoneof,$(1),RELEASABLES FINAL),)
+	$(call startrawoutput) \
+	echo "$(call whatLogOpen)" ; \
+	$(foreach V,$(EXTMAKEFILEPARAMETERS),$(V)='$($(V))') EXTMAKEFILETARGET='RELEASABLES' \
+	$(if $(USENMAKE),export MAKEFLAGS="";cd "$(subst /,\,$(DIRECTORY))";,) export EPOCROOT="$(strip $(OLDSTYLE_EPOCROOT))\"; export CFG=$(CFG_uppercase); \
+	$(MAKEVAR) $(if $(USENMAKE),-C -S,-C "$(subst /,\,$(DIRECTORY))" --no-print-directory) -f "$(EXTMAKEFILENAME)" \
+	CFG=$(CFG_uppercase) EPOCBLD="$(subst /,\,$(EPOCBLD))" TO_BLDINF="$(subst /,\,$(TO_BLDINF))" PLATFORM=$(PLATFORM) RELEASABLES | \
+	(read -r LINE; while [ $$$$? -eq 0 ]; do \
+	if [[ ! $$$$LINE =~ "Nothing to be done for"  ]] ; then echo "$(call whatLogItem,EM,$$$$LINE)"; fi; \
+	read -r LINE; done; ); \
+	echo "$(call whatLogClose)" \
+	$(call endrawoutput)
+
+
+WHATGNUEM:: $(UNIQ)_RELEASABLES
+
+endif
+endef
+
+DO_NOTHING:: $(UNIQ)_DO_NOTHING 
+$(UNIQ)_DO_NOTHING: ;
+
+$(foreach EXTTRG,$(EXTMAKETARGETS),$(eval $(call callgnumake,$(EXTTRG))))
+
+## Do ROMFILE target in romstuff.mke
+ifeq ($(ROMFILE_$(call sanitise,$(EXTMAKEFILENAME))),)
+ROMFILE_$(call sanitise,$(EXTMAKEFILENAME)):=1
+
+ROMDIR:=$(subst $(OLD_EPOCROOT),$(OLD_EPOCROOT)epoc32/rom/,$(TO_BLDINF))
+
+define RomfileRomstuff
+ROMFILE::
+	@$(MAKEVAR) --no-print-directory $(if $(USENMAKE),,-C "$(subst /,\,$(DIRECTORY))") -f "$(EXTMAKEFILENAME)" ROMFILE >> $(ROMDIR)/ARMV5TEST.IBY
+endef
+
+$(eval $(call RomfileRomstuff))
+endif
--- a/sbsv2/raptor/lib/flm/grouping.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/grouping.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,29 +1,29 @@
-# 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:
-#
-
-
-$(ALLTARGET): /:=$(/)
-$(ALLTARGET): FLMHOME:=$(FLMHOME)
-$(ALLTARGET): COMPONENT_ALLTARGETS:=$(COMPONENT_ALLTARGETS)
-$(ALLTARGET): COMPONENT_GLUEMAKEFILES:=$(COMPONENT_GLUEMAKEFILES)
-
-
-.PHONY:: $(ALLTARGET)
-$(ALLTARGET):: $(COMPONENT_ALLTARGETS)
-
-
-$(foreach COMPONENT_INC,$(COMPONENT_GLUEMAKEFILES),$(eval include $(COMPONENT_INC)))
-
-
+# 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:
+#
+
+
+$(ALLTARGET): /:=$(/)
+$(ALLTARGET): FLMHOME:=$(FLMHOME)
+$(ALLTARGET): COMPONENT_ALLTARGETS:=$(COMPONENT_ALLTARGETS)
+$(ALLTARGET): COMPONENT_GLUEMAKEFILES:=$(COMPONENT_GLUEMAKEFILES)
+
+
+.PHONY:: $(ALLTARGET)
+$(ALLTARGET):: $(COMPONENT_ALLTARGETS)
+
+
+$(foreach COMPONENT_INC,$(COMPONENT_GLUEMAKEFILES),$(eval include $(COMPONENT_INC)))
+
+
--- a/sbsv2/raptor/lib/flm/metaflm.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/metaflm.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,224 +1,224 @@
-#
-# 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: 
-#
-
-
-# Macros for creating Standard targets
-
-ifeq ($(_METAFLM_MK_),)
-_METAFLM_MK_:=1
-
-# GENERATE STANDARD CLEAN TARGET 
-# example usage:
-# $(eval $(call GenerateStandardCleanTarget,$(FILE_LIST),$(DIRECTORY_LIST)))
-
-## CLEAN macros #####################################
-# The clean macro does not generate a target but extension makefiles do have
-# CLEAN targets that need to be attached to something.
-.PHONY:: CLEAN
-
-define GenerateStandardCleanTarget
-$(info <clean bldinf='$(COMPONENT_META)' mmp='$(PROJECT_META)' config='$(SBS_CONFIGURATION)'>)
-$(foreach ITEM,$(1),$(info <file>$(ITEM)</file>))
-$(foreach ITEM,$(2),$(info <dir>$(ITEM)</dir>))
-$(info </clean>)
-endef
-
-## End CLEAN macros #####################################
-
-
-## WHAT macros #####################################
-
-
-## Begin --what Macros #####
-define outputWhat
-ifeq ($(OSTYPE),cygwin)
-$(2)::
-	@for FILE in $(subst %20,$(CHAR_SPACE),$(subst /,\\,$(call dblquote,$(1)))); do \
-		echo $$$$FILE; \
-	done;
-else
-$(2)::
-	@for FILE in $(subst %20,$(CHAR_SPACE),$(1)); do \
-		echo $$$$FILE; \
-	done
-endif
-endef
-
-## End --what Macros #####
-
-## Begin .whatlog Macros #####
-define whatLogOpen
-<whatlog bldinf='$(COMPONENT_META)' mmp='$(PROJECT_META)' config='$(SBS_CONFIGURATION)'>
-endef
-
-define whatLogItem
-$(if $(findstring EXPORT,$(1)),<export ,$(if $(findstring RESOURCE,$(1)),<resource>,$(if $(findstring BITMAP,$(1)),<bitmap>,$(if $(findstring STRINGTABLE,$(1)),<stringtable>,$(if $(findstring ARCHIVE,$(1)),<member>,<build>)))))$(subst %20,$(CHAR_SPACE),$(2))$(if $(findstring EXPORT,$(1)),/>,$(if $(findstring RESOURCE,$(1)),</resource>,$(if $(findstring BITMAP,$(1)),</bitmap>,$(if $(findstring STRINGTABLE,$(1)),</stringtable>,$(if $(findstring ARCHIVE,$(1)),</member>,</build>)))))
-endef
-
-define whatLogClose
-</whatlog>
-endef
-
-define outputWhatLog
-$(info $(call whatLogOpen))
-$(foreach ITEM,$(1),$(info $(call whatLogItem,$(2),$(ITEM))))
-$(info $(call whatLogClose))
-endef
-
-## End .whatlog Macros #####
-
-# General FLM entry points for what-related processing
-define WhatExports
-endef
-
-define whatmacro
-$(call outputWhatLog,$(1),$(2))
-endef
-
-define whatUnzip
-endef	
-## END WHAT UNZIP MACRO 
-
-## End WHAT macros #####################################
-
-# Macro for creating the test BATCH files.
-# Arguments: $(1) -> Target Name $(2) -> Output Batch file path
-define MakeTestBatchFiles
-    $(if $(BATCHFILE_CREATED_$(2))
-        ,
-            $(if $(TARGET_CREATED_$(2)_$(TARGET))
-                ,
-                ,
-                    $$(shell echo -e "$(1)\r" >> $(2))
-            )
-       	,
-       	    $$(shell $(GNUMKDIR) -p $(dir $(2)))
-       	    $$(shell echo -e "$(1)\r" > $(2))
-    )
-endef
-
-## path creation #########################
-# Make the destination directory if neccessary.  For some
-# make engines we must do this outside the rule or they
-# get confused by the apparent way in which different rules
-# can create a particular directory and they infer some kind
-# of dependency.
-
-# Makepath. Copyright (C) 2008 Symbian Software Ltd.
-# buffering with repeat prevention, makes directories after every 30 calls. Any more might overload 
-# the createprocess limit on arguments.
-#
-# makepathLIST is initialised in globals.mk
-define makepath_single
-$(if $(findstring $1,$(makepathLIST)),,$(eval makepathLIST:=$(makepathLIST) $1))
-$(if $(subst 30,,$(words $(makepathLIST))),,$(shell $(GNUMKDIR) -p $(makepathLIST))$(eval makepathLIST:=))
-endef
-
-# The following turns out to be extremely slow - something to do with using eval 
-# or to do with creating huge numbers of TARGET_ variables? BTW, this is an attempt
-# to not make things that we have already made.
-# define makepath
-# $(info makepath_start)$(foreach DIR,$1,$(if $(TARGET_$(1)),,$(call makepath_single,$(DIR))$(eval TARGET_$(1):=1)))$(info makepath_end)
-# endef
-
-# In general, makepath creates directories during FLM evaluation.
-# However, if the WHAT target is being processed then it should do nothing.
-ifeq ($(filter WHAT,$(call uppercase,$(MAKECMDGOALS))),)
-define makepath
-$(strip $(foreach DIR,$(sort $1),$(call makepath_single,$(DIR))))
-endef
-else
-define makepath
-endef
-endif
-
-
-define makepathfor
-$(call makepath,$(dir $1))
-endef
-
-# Make any remaining paths in the path buffer
-define makepathfinalise
-$(strip $(if $(makepathLIST),$(shell $(GNUMKDIR) -p $(makepathLIST))$(eval makepathLIST:=),))
-endef
-
-## ROMFILE macro #####################################
-define DoRomSet
-
-ifeq ($(call uppercase,$(TARGETTYPE)),LIB)
-BUILDROMTARGET:=
-endif
-
-ifeq ($(call uppercase,$(TARGETTYPE)),KEXT)
-ROMFILETYPE:=extension[MAGIC]
-ABIDIR:=KMAIN
-endif
-ifeq ($(call uppercase,$(TARGETTYPE)),LDD)
-ROMFILETYPE:=device[MAGIC]
-ABIDIR:=KMAIN
-endif
-ifeq ($(call uppercase,$(TARGETTYPE)),PDD)
-ROMFILETYPE:=device[MAGIC]
-ABIDIR:=KMAIN
-endif
-ifeq ($(call uppercase,$(TARGETTYPE)),VAR)
-ROMFILETYPE:=variant[MAGIC]
-ABIDIR:=KMAIN
-endif
-ifeq ($(call uppercase,$(TARGETTYPE)),KDLL)
-ABIDIR:=KMAIN
-endif
-
-ifneq ($(CALLDLLENTRYPOINTS),)
-ROMFILETYPE:=dll
-endif
-ifeq ($(ROMFILETYPE),primary)
-ABIDIR:=KMAIN
-endif
-
-endef
-
-## End of ROMFILE macro ##############################
-
-## Macros for writing FLMs without needing to know eval
-
-# declaring targets as RELEASABLE, for example,
-#
-# $(call raptor_release,$(TARGET1) $(TARGET2),RESOURCE)
-#
-# the optional type (RESOURCE) can be one of,
-# EXPORT RESOURCE BITMAP STRINGTABLE ARCHIVE
-#
-# no argument means just a default (binary) releasable.
-#
-define raptor_release
-$(eval $(call outputWhatLog,$1,$2))
-endef
-
-# declaring things that need to be cleaned.
-#
-# any files which are generated but are not RELEASABLE should be listed
-# using this macro, for example,
-#
-# $(call raptor_clean,$(OBJECT_FILES))
-#
-define raptor_clean
-$(eval $(call GenerateStandardCleanTarget,$1))
-endef
-
-endif 
-# end of metaflm
-## END TEST BATCH FILES MACRO
+#
+# 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: 
+#
+
+
+# Macros for creating Standard targets
+
+ifeq ($(_METAFLM_MK_),)
+_METAFLM_MK_:=1
+
+# GENERATE STANDARD CLEAN TARGET 
+# example usage:
+# $(eval $(call GenerateStandardCleanTarget,$(FILE_LIST),$(DIRECTORY_LIST)))
+
+## CLEAN macros #####################################
+# The clean macro does not generate a target but extension makefiles do have
+# CLEAN targets that need to be attached to something.
+.PHONY:: CLEAN
+
+define GenerateStandardCleanTarget
+$(info <clean bldinf='$(COMPONENT_META)' mmp='$(PROJECT_META)' config='$(SBS_CONFIGURATION)'>)
+$(foreach ITEM,$(1),$(info <file>$(ITEM)</file>))
+$(foreach ITEM,$(2),$(info <dir>$(ITEM)</dir>))
+$(info </clean>)
+endef
+
+## End CLEAN macros #####################################
+
+
+## WHAT macros #####################################
+
+
+## Begin --what Macros #####
+define outputWhat
+ifeq ($(OSTYPE),cygwin)
+$(2)::
+	@for FILE in $(subst %20,$(CHAR_SPACE),$(subst /,\\,$(call dblquote,$(1)))); do \
+		echo $$$$FILE; \
+	done;
+else
+$(2)::
+	@for FILE in $(subst %20,$(CHAR_SPACE),$(1)); do \
+		echo $$$$FILE; \
+	done
+endif
+endef
+
+## End --what Macros #####
+
+## Begin .whatlog Macros #####
+define whatLogOpen
+<whatlog bldinf='$(COMPONENT_META)' mmp='$(PROJECT_META)' config='$(SBS_CONFIGURATION)'>
+endef
+
+define whatLogItem
+$(if $(findstring EXPORT,$(1)),<export ,$(if $(findstring RESOURCE,$(1)),<resource>,$(if $(findstring BITMAP,$(1)),<bitmap>,$(if $(findstring STRINGTABLE,$(1)),<stringtable>,$(if $(findstring ARCHIVE,$(1)),<member>,<build>)))))$(subst %20,$(CHAR_SPACE),$(2))$(if $(findstring EXPORT,$(1)),/>,$(if $(findstring RESOURCE,$(1)),</resource>,$(if $(findstring BITMAP,$(1)),</bitmap>,$(if $(findstring STRINGTABLE,$(1)),</stringtable>,$(if $(findstring ARCHIVE,$(1)),</member>,</build>)))))
+endef
+
+define whatLogClose
+</whatlog>
+endef
+
+define outputWhatLog
+$(info $(call whatLogOpen))
+$(foreach ITEM,$(1),$(info $(call whatLogItem,$(2),$(ITEM))))
+$(info $(call whatLogClose))
+endef
+
+## End .whatlog Macros #####
+
+# General FLM entry points for what-related processing
+define WhatExports
+endef
+
+define whatmacro
+$(call outputWhatLog,$(1),$(2))
+endef
+
+define whatUnzip
+endef	
+## END WHAT UNZIP MACRO 
+
+## End WHAT macros #####################################
+
+# Macro for creating the test BATCH files.
+# Arguments: $(1) -> Target Name $(2) -> Output Batch file path
+define MakeTestBatchFiles
+    $(if $(BATCHFILE_CREATED_$(2))
+        ,
+            $(if $(TARGET_CREATED_$(2)_$(TARGET))
+                ,
+                ,
+                    $$(shell echo -e "$(1)\r" >> $(2))
+            )
+       	,
+       	    $$(shell $(GNUMKDIR) -p $(dir $(2)))
+       	    $$(shell echo -e "$(1)\r" > $(2))
+    )
+endef
+
+## path creation #########################
+# Make the destination directory if neccessary.  For some
+# make engines we must do this outside the rule or they
+# get confused by the apparent way in which different rules
+# can create a particular directory and they infer some kind
+# of dependency.
+
+# Makepath. Copyright (C) 2008 Symbian Software Ltd.
+# buffering with repeat prevention, makes directories after every 30 calls. Any more might overload 
+# the createprocess limit on arguments.
+#
+# makepathLIST is initialised in globals.mk
+define makepath_single
+$(if $(findstring $1,$(makepathLIST)),,$(eval makepathLIST:=$(makepathLIST) $1))
+$(if $(subst 30,,$(words $(makepathLIST))),,$(shell $(GNUMKDIR) -p $(makepathLIST))$(eval makepathLIST:=))
+endef
+
+# The following turns out to be extremely slow - something to do with using eval 
+# or to do with creating huge numbers of TARGET_ variables? BTW, this is an attempt
+# to not make things that we have already made.
+# define makepath
+# $(info makepath_start)$(foreach DIR,$1,$(if $(TARGET_$(1)),,$(call makepath_single,$(DIR))$(eval TARGET_$(1):=1)))$(info makepath_end)
+# endef
+
+# In general, makepath creates directories during FLM evaluation.
+# However, if the WHAT target is being processed then it should do nothing.
+ifeq ($(filter WHAT,$(call uppercase,$(MAKECMDGOALS))),)
+define makepath
+$(strip $(foreach DIR,$(sort $1),$(call makepath_single,$(DIR))))
+endef
+else
+define makepath
+endef
+endif
+
+
+define makepathfor
+$(call makepath,$(dir $1))
+endef
+
+# Make any remaining paths in the path buffer
+define makepathfinalise
+$(strip $(if $(makepathLIST),$(shell $(GNUMKDIR) -p $(makepathLIST))$(eval makepathLIST:=),))
+endef
+
+## ROMFILE macro #####################################
+define DoRomSet
+
+ifeq ($(call uppercase,$(TARGETTYPE)),LIB)
+BUILDROMTARGET:=
+endif
+
+ifeq ($(call uppercase,$(TARGETTYPE)),KEXT)
+ROMFILETYPE:=extension[MAGIC]
+ABIDIR:=KMAIN
+endif
+ifeq ($(call uppercase,$(TARGETTYPE)),LDD)
+ROMFILETYPE:=device[MAGIC]
+ABIDIR:=KMAIN
+endif
+ifeq ($(call uppercase,$(TARGETTYPE)),PDD)
+ROMFILETYPE:=device[MAGIC]
+ABIDIR:=KMAIN
+endif
+ifeq ($(call uppercase,$(TARGETTYPE)),VAR)
+ROMFILETYPE:=variant[MAGIC]
+ABIDIR:=KMAIN
+endif
+ifeq ($(call uppercase,$(TARGETTYPE)),KDLL)
+ABIDIR:=KMAIN
+endif
+
+ifneq ($(CALLDLLENTRYPOINTS),)
+ROMFILETYPE:=dll
+endif
+ifeq ($(ROMFILETYPE),primary)
+ABIDIR:=KMAIN
+endif
+
+endef
+
+## End of ROMFILE macro ##############################
+
+## Macros for writing FLMs without needing to know eval
+
+# declaring targets as RELEASABLE, for example,
+#
+# $(call raptor_release,$(TARGET1) $(TARGET2),RESOURCE)
+#
+# the optional type (RESOURCE) can be one of,
+# EXPORT RESOURCE BITMAP STRINGTABLE ARCHIVE
+#
+# no argument means just a default (binary) releasable.
+#
+define raptor_release
+$(eval $(call outputWhatLog,$1,$2))
+endef
+
+# declaring things that need to be cleaned.
+#
+# any files which are generated but are not RELEASABLE should be listed
+# using this macro, for example,
+#
+# $(call raptor_clean,$(OBJECT_FILES))
+#
+define raptor_clean
+$(eval $(call GenerateStandardCleanTarget,$1))
+endef
+
+endif 
+# end of metaflm
+## END TEST BATCH FILES MACRO
--- a/sbsv2/raptor/lib/flm/msvctools.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/msvctools.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,212 +1,205 @@
-# 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:
-# MSVC TOOLS EXE/LIB Function Like Makefile (FLM)
-# Knows how to build all possible executables for the TOOLS build
-# 
-#
-
-CLEANTARGETS:=
-RELEASABLES:=
-INSTALLTARGET:=
-
-RELEASEPATH:=$(RELEASEPATHROOT)/$(FULLVARIANTPATH)
-BUILDPATH:=$(OUTPUTPATH)/$(FULLVARIANTPATH)
-RELEASETARGET:=$(RELEASEPATH)/$(TARGET).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(TARGETTYPE))
-
-# make the output directories while reading makefile - some build engines prefer this
-$(call makepath,$(RELEASEPATH))
-$(call makepath,$(BUILDPATH))
-
-CLEANTARGETS:=$(CLEANTARGETS) $(RELEASETARGET)
-RELEASEABLES:=$(RELEASEABLES) $(RELEASETARGET)
-
-GENDEBUGINFO:=$(if $(findstring deb,$(VARIANTTYPE)),1,)
-
-# MSVC "no space" arguments must take the form /<ARG><PATH_WITH_DOS_SLASHES> e.g.
-# 	/FoF:\object\file\to\be\created.obj
-define msvcformatarg
-	$(1)$(subst /,\\\,$(2))
-endef
-
-#############
-## COMPILE ##
-#############
-
-# object files and related
-OBJFILES:=$(patsubst %,$(BUILDPATH)/%.obj,$(basename $(notdir $(SOURCE))))
-SBRFILES:=$(addsuffix .sbr, $(basename $(OBJFILES)))
-LISFILES:=$(addsuffix .lis, $(basename $(OBJFILES)))
-LSTFILES:=$(addsuffix .tools.lst, $(basename $(SOURCE)))
-CLEANTARGETS:=$(CLEANTARGETS) $(OBJFILES) $(SBRFILES) $(LISFILES) $(LSTFILES)
-
-# include paths and preinclude file
-UINCLUDE:=$(patsubst %,$(OPT.USERINCLUDE)%,$(USERINCLUDE))
-SINCLUDE:=$(patsubst %,$(OPT.SYSINCLUDE)%,$(SYSTEMINCLUDE))
-PINCLUDE:=$(OPT.PREINCLUDE)$(notdir $(PRODUCT_INCLUDE))
-INCLUDES:=$(PINCLUDE) $(UINCLUDE) $(SINCLUDE)
-
-# macros
-DEFINES:=$(call makemacrodef,$(OPT.DEFINE),$(CDEFS) $(BASE_MACRO) $(CFLAGS.ADD))
-
-# other
-PDBFILE:=$(if $(GENDEBUGINFO),$(RELEASEPATH)/$(TARGET).pdb,)
-CLEANTARGETS:=$(CLEANTARGETS) $(PDBFILE)
-
-#compile
-define msvctoolscompile
-  $(BUILDPATH)/$(basename $(notdir $(1))).obj: $(1) $(PROJECT_META) $(if $(HAVE_ORDERONLY),|,)  EXPORT
-	$(call startrule,msvctoolscompile,,$(1)) \
-	$(CC) \
-	$(if $(findstring staticlib,$(BASE_TYPE)),,$(CFLAGS.LIB)) \
-	$(CFLAGS) $$(subst /,-,$(OPTION_MSVC)) \
-	$(if $(findstring /W,$(OPTION_MSVC)),,$(CFLAGS.DEFAULT.WARNLEVEL)) \
-	$(if $(PDBFILE),$$(call msvcformatarg,$(OPT.PDBFILE),$(PDBFILE)),) \
-	$(DEFINES) $(INCLUDES) \
-	$$(call msvcformatarg,$(OPT.BROWSEFILE),$(BUILDPATH)/$(basename $(notdir $(1))).sbr) \
-	$$(call msvcformatarg,$(OPT.OBJECTFILE),$$@) $(1) \
-	$(call endrule,msvctoolscompile)
-endef
-# make the output directories while reading makefile - some build engines prefer this
-$(call makepath,$(BUILDPATH))
-$(foreach SRCFILE,$(SOURCE),$(eval $(call msvctoolscompile,$(SRCFILE))))
-
-# assembler listing
-define msvctoolslisting
-  LISTING:: $(BUILDPATH)/$(basename $(notdir $(1))).lis
-	$(GNUCP) $$< $(basename $(1)).tools.lst
-  
-  $(BUILDPATH)/$(basename $(notdir $(1))).lis: $(1)
-	$(call startrule,msvctoolslisting) \
-	$(CC) \
-	$(if $(findstring staticlib,$(BASE_TYPE)),,$(CFLAGS.LIB)) \
-	$(CFLAGS) $$(subst /,-,$(OPTION_MSVC)) \
-	$(if $(findstring /W,$(OPTION_MSVC)),,$(CFLAGS.DEFAULT.WARNLEVEL)) \
-	$(DEFINES) $(INCLUDES) \
-	$$(call msvcformatarg,$(OPT.LISTING),$(BUILDPATH)/$(basename $(notdir $(1))).lis) \
-	$(1) \
-	$(call endrule,msvctoolslisting)
-
-  endef
-$(foreach SRCFILE,$(SOURCE),$(eval $(call msvctoolslisting,$(SRCFILE))))
-
-
-ifeq ($(BASE_TYPE),staticlib)
-
-  #############
-  ## ARCHIVE ##
-  #############
-
-  ARCHIVERRESPONSEFILE:=$(BUILDPATH)/$(TARGET).arf
-  CLEANTARGETS:=$(CLEANTARGETS) $(ARCHIVERRESPONSEFILE)
-
-  define msvctoolsarchive
-    $(RELEASETARGET): $(OBJFILES)
-	  @echo "" > $(ARCHIVERRESPONSEFILE);
-	  $(call groupin10infile,$(ARCHIVERRESPONSEFILE),$(OBJFILES)) ;
-	  $(call startrule,msvctoolsarchive) \
-	  $(AR) $(ARFLAGS) $(OPT.SUBSYSTEM)$(SUBSYSTEM) $$(call msvcformatarg,$(OPT.OUTFILE),$$@) \
-	  $$(call msvcformatarg,$(PREFIX.RESPONSEFILE),$(ARCHIVERRESPONSEFILE)) \
-	  $(if $(SAVESPACE),; $(GNURM) -f $(OBJFILES); true,) \
-	  $(call endrule,msvctoolsarchive)
-
-  endef
-  $(eval $(msvctoolsarchive))
-
-else
-
-  ##########
-  ## LINK ##
-  ##########
-
-  STATICLIBS:=$(patsubst %,$(RELEASEPATH)/%.lib,$(STATICLIBRARY))
-  IMPORTLIBS:=$(patsubst %.dso,$(IMPORTLIBPATH)/%.lib,$(LIBRARY))
-  LINKERRESPONSEFILE:=$(BUILDPATH)/$(TARGET).lrf
-  CLEANTARGETS:=$(CLEANTARGETS) $(RELEASETARGET).lib $(LINKERRESPONSEFILE)
-  
-  define msvctoolslink
-    $(RELEASETARGET): $(OBJFILES) $(STATICLIBS) $(IMPORTLIBS)
-	  @echo "" > $(LINKERRESPONSEFILE);
-	  $(call groupin10infile,$(LINKERRESPONSEFILE),$(STATICLIBS) $(IMPORTLIBS) $(OBJFILES)) ;
-	  $(call startrule,msvctoolslink) \
-	  $(LD) $(LFLAGS) $(WIN32_LIBRARY) $(OPT.SUBSYSTEM)$(SUBSYSTEM) \
-	  $$(call msvcformatarg,$(OPT.OUTFILE),$$@) \
-	  $$(call msvcformatarg,$(OPT.IMPLIB),$(RELEASETARGET).lib) \
-	  $$(call msvcformatarg,$(PREFIX.RESPONSEFILE),$(LINKERRESPONSEFILE)) \
-	  $(if $(SAVESPACE),; $(GNURM) -f $(OBJFILES); true,) \
-	  $(call endrule,msvctoolslink)
-  endef
-  $(eval $(msvctoolslink)) 
-
-endif
-
-
-#############
-## INSTALL ##
-#############
-
-ifneq ($(INSTALLPATH),)
-  INSTALLTARGET:=$(INSTALLPATH)/$(TARGET).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(TARGETTYPE))
-  CLEANTARGETS:=$(CLEANTARGETS) $(INSTALLTARGET)
-  RELEASEABLES:=$(RELEASEABLES) $(INSTALLTARGET)
-
-  define msvctoolsinstall
-    $(INSTALLTARGET): $(RELEASETARGET)
-	  $(call startrule,msvctoolsinstall) \
-	  $(GNUCP) $$< $$@ && \
-	  $(GNUCHMOD) a+rwx $$@ \
-	  $(call endrule,msvctoolsinstall)
-  endef
-  # make the output directories while reading makefile - some build engines prefer this
-  $(call makepath,$(INSTALLPATH))
-  $(eval $(msvctoolsinstall))
-endif
-
-
-##########################
-## BROWSE DB GENERATION ##
-##########################
-
-ifneq ($(GENDEBUGINFO),)
-  BSCFILE:=$(RELEASEPATH)/$(TARGET).bsc
-  BSCRESPONSEFILE:=$(BUILDPATH)/$(TARGET).brf
-  CLEANTARGETS:=$(CLEANTARGETS) $(BSCFILE) $(BSCRESPONSEFILE)
-  RELEASEABLES:=$(RELEASEABLES) $(BSCFILE)
-
-  define msvctoolsgenbrowse  
-    $(BSCFILE): $(OBJFILES)
-	  @echo "" > $(BSCRESPONSEFILE);
-	  $(call groupin10infile,$(BSCRESPONSEFILE),$(SBRFILES)) ;
-	  $(call startrule,msvctoolsgenbrowse) \
-	  $(BROWSETOOL) $(BROWSEFLAGS) $$(call msvcformatarg,$(OPT.BROWSEDB),$$@) \
-	  $$(call msvcformatarg,$(PREFIX.RESPONSEFILE),$(BSCRESPONSEFILE)) \
-	  $(if $(SAVESPACE),; $(GNURM) -f $(SBRFILES); true,) \
-	  $(call endrule,msvctoolsgenbrowse)
-  endef
-  $(eval $(msvctoolsgenbrowse)) 
-endif
-
-
-# Global targets
-.PHONY:: $(ALLTARGET)
-$(ALLTARGET):: $(RELEASEABLES)
-TARGET:: $(RELEASEABLES)
-
-ifeq ($(BASE_TYPE),staticlib)
-  LIBRARY:: $(RELEASETARGET) $(INSTALLTARGET)
-endif
-
-# clean up
-$(eval $(call GenerateStandardCleanTarget,$(CLEANTARGETS),,))
-# for the abld -what target
-$(eval $(call whatmacro,$(INSTALLTARGET),WHATTOOLS))
+# Copyright (c) 2008-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:
+# MSVC TOOLS EXE/LIB Function Like Makefile (FLM)
+# Knows how to build all possible executables for the TOOLS build
+# 
+#
+
+CLEANTARGETS:=
+RELEASABLES:=
+INSTALLTARGET:=
+
+RELEASEPATH:=$(RELEASEPATHROOT)/$(FULLVARIANTPATH)
+BUILDPATH:=$(OUTPUTPATH)/$(FULLVARIANTPATH)
+RELEASETARGET:=$(RELEASEPATH)/$(TARGET).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(TARGETTYPE))
+
+# make the output directories while reading makefile - some build engines prefer this
+$(call makepath,$(RELEASEPATH))
+$(call makepath,$(BUILDPATH))
+
+RELEASABLES:=$(RELEASABLES) $(RELEASETARGET)
+
+GENDEBUGINFO:=$(if $(findstring deb,$(VARIANTTYPE)),1,)
+
+# MSVC "no space" arguments must take the form /<ARG><PATH_WITH_DOS_SLASHES> e.g.
+# 	/FoF:\object\file\to\be\created.obj
+define msvcformatarg
+	$(1)$(subst /,\\\,$(2))
+endef
+
+#############
+## COMPILE ##
+#############
+
+# object files and related
+OBJFILES:=$(patsubst %,$(BUILDPATH)/%.obj,$(basename $(notdir $(SOURCE))))
+SBRFILES:=$(addsuffix .sbr, $(basename $(OBJFILES)))
+LISFILES:=$(addsuffix .lis, $(basename $(OBJFILES)))
+LSTFILES:=$(addsuffix .tools.lst, $(basename $(SOURCE)))
+CLEANTARGETS:=$(CLEANTARGETS) $(OBJFILES) $(SBRFILES) $(LISFILES) $(LSTFILES)
+
+# include paths and preinclude file
+UINCLUDE:=$(patsubst %,$(OPT.USERINCLUDE)%,$(USERINCLUDE))
+SINCLUDE:=$(patsubst %,$(OPT.SYSINCLUDE)%,$(SYSTEMINCLUDE))
+PINCLUDE:=$(OPT.PREINCLUDE)$(notdir $(PRODUCT_INCLUDE))
+INCLUDES:=$(PINCLUDE) $(UINCLUDE) $(SINCLUDE)
+
+# macros
+DEFINES:=$(call makemacrodef,$(OPT.DEFINE),$(CDEFS) $(BASE_MACRO) $(CFLAGS.ADD))
+
+#compile
+define msvctoolscompile
+  $(BUILDPATH)/$(basename $(notdir $(1))).obj: $(1) $(PROJECT_META) $(if $(HAVE_ORDERONLY),|,)  EXPORT
+	$(call startrule,msvctoolscompile,,$(1)) \
+	$(CC) \
+	$(if $(findstring staticlib,$(BASE_TYPE)),,$(CFLAGS.LIB)) \
+	$(CFLAGS) $$(subst /,-,$(OPTION_MSVC)) \
+	$(if $(findstring /W,$(OPTION_MSVC)),,$(CFLAGS.DEFAULT.WARNLEVEL)) \
+	$(DEFINES) $(INCLUDES) \
+	$$(call msvcformatarg,$(OPT.BROWSEFILE),$(BUILDPATH)/$(basename $(notdir $(1))).sbr) \
+	$$(call msvcformatarg,$(OPT.OBJECTFILE),$$@) $(1) \
+	$(call endrule,msvctoolscompile)
+endef
+# make the output directories while reading makefile - some build engines prefer this
+$(call makepath,$(BUILDPATH))
+$(foreach SRCFILE,$(SOURCE),$(eval $(call msvctoolscompile,$(SRCFILE))))
+
+# assembler listing
+define msvctoolslisting
+  LISTING:: $(BUILDPATH)/$(basename $(notdir $(1))).lis
+	$(GNUCP) $$< $(basename $(1)).tools.lst
+  
+  $(BUILDPATH)/$(basename $(notdir $(1))).lis: $(1)
+	$(call startrule,msvctoolslisting) \
+	$(CC) \
+	$(if $(findstring staticlib,$(BASE_TYPE)),,$(CFLAGS.LIB)) \
+	$(CFLAGS) $$(subst /,-,$(OPTION_MSVC)) \
+	$(if $(findstring /W,$(OPTION_MSVC)),,$(CFLAGS.DEFAULT.WARNLEVEL)) \
+	$(DEFINES) $(INCLUDES) \
+	$$(call msvcformatarg,$(OPT.LISTING),$(BUILDPATH)/$(basename $(notdir $(1))).lis) \
+	$(1) \
+	$(call endrule,msvctoolslisting)
+
+  endef
+$(foreach SRCFILE,$(SOURCE),$(eval $(call msvctoolslisting,$(SRCFILE))))
+
+
+ifeq ($(BASE_TYPE),staticlib)
+
+  #############
+  ## ARCHIVE ##
+  #############
+
+  ARCHIVERRESPONSEFILE:=$(BUILDPATH)/$(TARGET).arf
+  CLEANTARGETS:=$(CLEANTARGETS) $(ARCHIVERRESPONSEFILE)
+
+  define msvctoolsarchive
+    $(RELEASETARGET): $(OBJFILES)
+	  @echo "" > $(ARCHIVERRESPONSEFILE);
+	  $(call groupin10infile,$(ARCHIVERRESPONSEFILE),$(OBJFILES)) ;
+	  $(call startrule,msvctoolsarchive) \
+	  $(AR) $(ARFLAGS) $(OPT.SUBSYSTEM)$(SUBSYSTEM) $$(call msvcformatarg,$(OPT.OUTFILE),$$@) \
+	  $$(call msvcformatarg,$(PREFIX.RESPONSEFILE),$(ARCHIVERRESPONSEFILE)) \
+	  $(if $(SAVESPACE),; $(GNURM) -f $(OBJFILES); true,) \
+	  $(call endrule,msvctoolsarchive)
+
+  endef
+  $(eval $(msvctoolsarchive))
+
+else
+
+  ##########
+  ## LINK ##
+  ##########
+
+  STATICLIBS:=$(patsubst %,$(RELEASEPATH)/%.lib,$(STATICLIBRARY))
+  IMPORTLIBS:=$(patsubst %.dso,$(IMPORTLIBPATH)/%.lib,$(LIBRARY))
+  LINKERRESPONSEFILE:=$(BUILDPATH)/$(TARGET).lrf
+  CLEANTARGETS:=$(CLEANTARGETS) $(RELEASETARGET).lib $(LINKERRESPONSEFILE)
+  
+  define msvctoolslink
+    $(RELEASETARGET): $(OBJFILES) $(STATICLIBS) $(IMPORTLIBS)
+	  @echo "" > $(LINKERRESPONSEFILE);
+	  $(call groupin10infile,$(LINKERRESPONSEFILE),$(STATICLIBS) $(IMPORTLIBS) $(OBJFILES)) ;
+	  $(call startrule,msvctoolslink) \
+	  $(LD) $(LFLAGS) $(WIN32_LIBRARY) $(OPT.SUBSYSTEM)$(SUBSYSTEM) \
+	  $$(call msvcformatarg,$(OPT.OUTFILE),$$@) \
+	  $$(call msvcformatarg,$(OPT.IMPLIB),$(RELEASETARGET).lib) \
+	  $$(call msvcformatarg,$(PREFIX.RESPONSEFILE),$(LINKERRESPONSEFILE)) \
+	  $(if $(SAVESPACE),; $(GNURM) -f $(OBJFILES); true,) \
+	  $(call endrule,msvctoolslink)
+  endef
+  $(eval $(msvctoolslink)) 
+
+endif
+
+
+#############
+## INSTALL ##
+#############
+
+ifneq ($(INSTALLPATH),)
+  INSTALLTARGET:=$(INSTALLPATH)/$(TARGET).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(TARGETTYPE))
+  RELEASABLES:=$(RELEASABLES) $(INSTALLTARGET)
+
+  define msvctoolsinstall
+    $(INSTALLTARGET): $(RELEASETARGET)
+	  $(call startrule,msvctoolsinstall) \
+	  $(GNUCP) $$< $$@ && \
+	  $(GNUCHMOD) a+rwx $$@ \
+	  $(call endrule,msvctoolsinstall)
+  endef
+  # make the output directories while reading makefile - some build engines prefer this
+  $(call makepath,$(INSTALLPATH))
+  $(eval $(msvctoolsinstall))
+endif
+
+
+##########################
+## BROWSE DB GENERATION ##
+##########################
+
+ifneq ($(GENDEBUGINFO),)
+  BSCFILE:=$(RELEASEPATH)/$(TARGET).bsc
+  BSCRESPONSEFILE:=$(BUILDPATH)/$(TARGET).brf
+  CLEANTARGETS:=$(CLEANTARGETS) $(BSCRESPONSEFILE)
+  RELEASABLES:=$(RELEASABLES) $(BSCFILE)
+
+  define msvctoolsgenbrowse  
+    $(BSCFILE): $(OBJFILES)
+	  @echo "" > $(BSCRESPONSEFILE);
+	  $(call groupin10infile,$(BSCRESPONSEFILE),$(SBRFILES)) ;
+	  $(call startrule,msvctoolsgenbrowse) \
+	  $(BROWSETOOL) $(BROWSEFLAGS) $$(call msvcformatarg,$(OPT.BROWSEDB),$$@) \
+	  $$(call msvcformatarg,$(PREFIX.RESPONSEFILE),$(BSCRESPONSEFILE)) \
+	  $(if $(SAVESPACE),; $(GNURM) -f $(SBRFILES); true,) \
+	  $(call endrule,msvctoolsgenbrowse)
+  endef
+  $(eval $(msvctoolsgenbrowse)) 
+endif
+
+
+# Global targets
+.PHONY:: $(ALLTARGET)
+$(ALLTARGET):: $(RELEASABLES)
+TARGET:: $(RELEASABLES)
+
+ifeq ($(BASE_TYPE),staticlib)
+  LIBRARY:: $(RELEASETARGET) $(INSTALLTARGET)
+endif
+
+# clean up
+$(call raptor_clean,$(CLEANTARGETS))
+# for the --what option and the log file
+$(call raptor_release,$(INSTALLTARGET))
--- a/sbsv2/raptor/lib/flm/msvctools.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/msvctools.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,79 +1,78 @@
-<?xml version='1.0' encoding='ISO-8859-1'?>
-<build xmlns='http://symbian.com/xml/build' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://symbian.com/xml/build ../../schema/build/2_0.xsd'>
-	<!-- Tools interfaces -->
-
-	<interface name='msvctools.flm' extends='base.flm' abstract='true'>
-		<param name='INSTALLPATH'/>
-		<param name='IMPORTLIBPATH'/>
-		<param name='OUTPUTPATH'/>
-		<param name='VARIANTPLATFORM'/>
-		<param name='PLATFORM' default='$(VARIANTPLATFORM)'/>
-		<param name='PRODUCT_INCLUDE'/>
-		<param name='RELEASEPATHROOT'/>
-		<param name='REQUESTEDTARGETEXT' default=''/>
-		<param name='VARIANTTYPE'/>
-		<param name='FULLVARIANTPATH'/>
-		<param name='PLATMACROS.WINDOWS'/>
-		<param name='PLATMACROS.LINUX'/>
-	</interface>
-
-	<interface name='msvctools.mmp' extends='msvctools.flm' abstract='true'>
-		<param name='LIBRARY' default=''/>
-		<param name='OPTION_MSVC' default=''/>
-		<param name='SOURCE' default=''/>
-		<param name='STATICLIBRARY' default=''/>
-		<param name='SYSTEMINCLUDE' default=''/>
-		<param name='TARGET'/>
-		<param name='TARGETPATH'/>
-		<param name='TARGETTYPE'/>
-		<param name='USERINCLUDE' default=''/>
-		<param name='WIN32_HEADERS' default=''/>
-		<param name='WIN32_LIBRARY' default=''/>
-	</interface>
-
-	<interface name='msvctools.toolchain' extends='msvctools.mmp' abstract='true'>
-		<param name='INCLUDE'/>
-		<param name='LIB'/>
-		<param name='OPT.BROWSEDB'/>
-		<param name='OPT.BROWSEFILE'/>
-		<param name='OPT.COMPILE'/>
-		<param name='OPT.DEFINE'/>
-		<param name='OPT.INCLUDE'/>
-		<param name='OPT.LISTING'/>
-		<param name='OPT.OBJECTFILE'/>
-		<param name='OPT.OUTFILE'/>
-		<param name='OPT.PDBFILE'/>
-		<param name='OPT.PREINCLUDE'/>
-		<param name='OPT.SUBSYSTEM'/>
-		<param name='OPT.SYSINCLUDE'/>
-		<param name='OPT.USERINCLUDE'/>
-		<param name='PREFIX.RESPONSEFILE'/>
-		<param name='BROWSETOOL'/>
-		<param name='BROWSEFLAGS'/>
-		<param name='CC'/>
-		<param name='CDEFS'/>
-		<param name='CFLAGS'/>
-		<param name='CFLAGS.DEFAULT.WARNLEVEL'/>
-		<param name='CFLAGS.LIB'/>
-	</interface>
-
-	<interface name='msvctools.exe' extends='msvctools.toolchain' flm='msvctools.flm'>
-		<param name='BASE_TYPE' default='exe'/>
-		<param name='BASE_MACRO' default='__EXE__'/>
-		<param name='LD'/>
-		<param name='LFLAGS'/>
-		<param name='OPT.IMPLIB'/>
-		<param name='CFLAGS.ADD' default=''/>
-		<param name='SUBSYSTEM' default='console'/>
-	</interface>
-
-	<interface name='msvctools.lib' extends='msvctools.toolchain' flm='msvctools.flm'>
-		<param name='BASE_TYPE' default='staticlib'/>
-		<param name='BASE_MACRO' default=''/>
-		<param name='AR'/>
-		<param name='ARFLAGS'/>
-		<param name='CFLAGS.ADD' default='_MT'/>
-		<param name='SUBSYSTEM' default='windows'/>
-	</interface>
-
-</build>
+<?xml version='1.0' encoding='ISO-8859-1'?>
+<build xmlns='http://symbian.com/xml/build' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://symbian.com/xml/build ../../schema/build/2_0.xsd'>
+	<!-- Tools interfaces -->
+
+	<interface name='msvctools.flm' extends='base.flm' abstract='true'>
+		<param name='INSTALLPATH'/>
+		<param name='IMPORTLIBPATH'/>
+		<param name='OUTPUTPATH'/>
+		<param name='VARIANTPLATFORM'/>
+		<param name='PLATFORM' default='$(VARIANTPLATFORM)'/>
+		<param name='PRODUCT_INCLUDE'/>
+		<param name='RELEASEPATHROOT'/>
+		<param name='REQUESTEDTARGETEXT' default=''/>
+		<param name='VARIANTTYPE'/>
+		<param name='FULLVARIANTPATH'/>
+		<param name='PLATMACROS.WINDOWS'/>
+		<param name='PLATMACROS.LINUX'/>
+	</interface>
+
+	<interface name='msvctools.mmp' extends='msvctools.flm' abstract='true'>
+		<param name='LIBRARY' default=''/>
+		<param name='OPTION_MSVC' default=''/>
+		<param name='SOURCE' default=''/>
+		<param name='STATICLIBRARY' default=''/>
+		<param name='SYSTEMINCLUDE' default=''/>
+		<param name='TARGET'/>
+		<param name='TARGETPATH'/>
+		<param name='TARGETTYPE'/>
+		<param name='USERINCLUDE' default=''/>
+		<param name='WIN32_HEADERS' default=''/>
+		<param name='WIN32_LIBRARY' default=''/>
+	</interface>
+
+	<interface name='msvctools.toolchain' extends='msvctools.mmp' abstract='true'>
+		<param name='INCLUDE'/>
+		<param name='LIB'/>
+		<param name='OPT.BROWSEDB'/>
+		<param name='OPT.BROWSEFILE'/>
+		<param name='OPT.COMPILE'/>
+		<param name='OPT.DEFINE'/>
+		<param name='OPT.INCLUDE'/>
+		<param name='OPT.LISTING'/>
+		<param name='OPT.OBJECTFILE'/>
+		<param name='OPT.OUTFILE'/>
+		<param name='OPT.PREINCLUDE'/>
+		<param name='OPT.SUBSYSTEM'/>
+		<param name='OPT.SYSINCLUDE'/>
+		<param name='OPT.USERINCLUDE'/>
+		<param name='PREFIX.RESPONSEFILE'/>
+		<param name='BROWSETOOL'/>
+		<param name='BROWSEFLAGS'/>
+		<param name='CC'/>
+		<param name='CDEFS'/>
+		<param name='CFLAGS'/>
+		<param name='CFLAGS.DEFAULT.WARNLEVEL'/>
+		<param name='CFLAGS.LIB'/>
+	</interface>
+
+	<interface name='msvctools.exe' extends='msvctools.toolchain' flm='msvctools.flm'>
+		<param name='BASE_TYPE' default='exe'/>
+		<param name='BASE_MACRO' default='__EXE__'/>
+		<param name='LD'/>
+		<param name='LFLAGS'/>
+		<param name='OPT.IMPLIB'/>
+		<param name='CFLAGS.ADD' default=''/>
+		<param name='SUBSYSTEM' default='console'/>
+	</interface>
+
+	<interface name='msvctools.lib' extends='msvctools.toolchain' flm='msvctools.flm'>
+		<param name='BASE_TYPE' default='staticlib'/>
+		<param name='BASE_MACRO' default=''/>
+		<param name='AR'/>
+		<param name='ARFLAGS'/>
+		<param name='CFLAGS.ADD' default='_MT'/>
+		<param name='SUBSYSTEM' default='windows'/>
+	</interface>
+
+</build>
--- a/sbsv2/raptor/lib/flm/none.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/none.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,27 +1,27 @@
-# 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:
-# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
-# Build Resources only
-# 
-#
-
-ifeq ($(TARGETTYPE),none)
-
-# Nothing to do here at the moment.  Perhaps later 
-# this will contain "all" rules to tie resources together
-
-else
-$(error none.flm called with wrong TARGETTYPE (should be 'none' but is '$(TARGETTYPE)'))
-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:
+# ARMv5 EXE/DLL ABIv2 Function Like Makefile (FLM)
+# Build Resources only
+# 
+#
+
+ifeq ($(TARGETTYPE),none)
+
+# Nothing to do here at the moment.  Perhaps later 
+# this will contain "all" rules to tie resources together
+
+else
+$(error none.flm called with wrong TARGETTYPE (should be 'none' but is '$(TARGETTYPE)'))
+endif
+
--- a/sbsv2/raptor/lib/flm/null.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/null.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,16 +1,16 @@
-# 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:
-# An empty FLM, for cases where no action is required
-# 
-#
+# 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:
+# An empty FLM, for cases where no action is required
+# 
+#
--- a/sbsv2/raptor/lib/flm/readme.txt	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/readme.txt	Wed Jun 23 16:56:47 2010 +0800
@@ -1,42 +1,42 @@
-Function-Like Makefiles
-------------------------
-
-Tests may be run from the "test" subdirectory.  Simply change into it and type 'make'.
-
-CHECKING YOUR BUILD ENVIRONMENT
---------------------------------
-In the test directory type "make envcheck" to see if you have correct path
-settings and determine if critical tools are available.
-
-FLMS
-----
-
-e32abiv2.flm    # PARENT FLM for building ARMv5 ABIv2 binaries
-e32abiv2.mk     # defaults makefile for building ARMv5 ABIv2 binaries 
-e32abiv2exe.flm # derived FLM (from e32abiv2.flm) for building ARMv5 ABIv2 exes
-e32abiv2dll.flm # derived FLM (from e32abiv2.flm) for building ARMv5 ABIv2 dlls
-example_exedll.flm # example flm
-extend_exe.flm  # example flm
-flmtools.mk     # utility functions for use in flms
-grouping.flm    # FLM for creating components
-metaflm.mk      # FLM for manipulating and working with other FLMS
-readme.txt	# This file
-rvct_armv5.mk   # defaults for ARMv5 ABIv2 parameters, used by e32abiv2.mk
-standard.xml	# interface file for e32abiv2.flm
-test		# ===== Base directory for all tests =====
-	Makefile # Glue makefile.  calls grouping.flm to bind all tests
-		 # together into a top-level target
-	basiclibs
-	dllabiv2_1
-	dllabiv2_defaults.mk
-	exeabiv2_1	# Test building a basic EXE
-	exeabiv2_2
-	exeabiv2_3
-	exeabiv2_defaults.mk
-tools			# ======= FLM related tools =======
-	command_diff.py # compare two commandlines to find what options are
-different
-	flm2if.py	# Produce an interface file from an FLM
-	flmcheck.py	# Check FLM for errors
-	flm.py		# Parse and manipulate flms
-	test_command_diff.sh
+Function-Like Makefiles
+------------------------
+
+Tests may be run from the "test" subdirectory.  Simply change into it and type 'make'.
+
+CHECKING YOUR BUILD ENVIRONMENT
+--------------------------------
+In the test directory type "make envcheck" to see if you have correct path
+settings and determine if critical tools are available.
+
+FLMS
+----
+
+e32abiv2.flm    # PARENT FLM for building ARMv5 ABIv2 binaries
+e32abiv2.mk     # defaults makefile for building ARMv5 ABIv2 binaries 
+e32abiv2exe.flm # derived FLM (from e32abiv2.flm) for building ARMv5 ABIv2 exes
+e32abiv2dll.flm # derived FLM (from e32abiv2.flm) for building ARMv5 ABIv2 dlls
+example_exedll.flm # example flm
+extend_exe.flm  # example flm
+flmtools.mk     # utility functions for use in flms
+grouping.flm    # FLM for creating components
+metaflm.mk      # FLM for manipulating and working with other FLMS
+readme.txt	# This file
+rvct_armv5.mk   # defaults for ARMv5 ABIv2 parameters, used by e32abiv2.mk
+standard.xml	# interface file for e32abiv2.flm
+test		# ===== Base directory for all tests =====
+	Makefile # Glue makefile.  calls grouping.flm to bind all tests
+		 # together into a top-level target
+	basiclibs
+	dllabiv2_1
+	dllabiv2_defaults.mk
+	exeabiv2_1	# Test building a basic EXE
+	exeabiv2_2
+	exeabiv2_3
+	exeabiv2_defaults.mk
+tools			# ======= FLM related tools =======
+	command_diff.py # compare two commandlines to find what options are
+different
+	flm2if.py	# Produce an interface file from an FLM
+	flmcheck.py	# Check FLM for errors
+	flm.py		# Parse and manipulate flms
+	test_command_diff.sh
--- a/sbsv2/raptor/lib/flm/resource.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/resource.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,301 +1,302 @@
-# 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:
-# Function Like Makefile (FLM) to create a resource header (.rsg)
-# and resource files (.rsc, .r01, .r02 etc.)
-#
-#
-
-## Parameters that are expected:
-# TARGET
-# TARGETPATH
-# LANGUAGES
-# HEADER
-# HEADERONLY
-# EPOCROOT
-# MMPDEFS
-# PRODUCT_INCLUDE
-# SYSTEMINCLUDE
-# USERINCLUDE
-# GNUCPP
-# GNUSED
-# RCOMP
-# OUTPUTPATH
-# SOURCE
-# BINCOPYDIRS
-
-
-# The rss is pre-processed once for each language and results
-# in a file with extension r$(LANGUAGE) where $(LANGUAGE) is
-# either "sc" or a 2 (or more) digit number.
-ifneq ($(TARGETPATH),)
-RSCDIR:=$(subst //,/,$(EPOCROOT)/epoc32/data/z/$(TARGETPATH))
-else
-RSCDIR:=$(subst //,/,$(EPOCROOT)/epoc32/data)
-endif
-RESBASE:=$(RSCDIR)/$(TARGET_lower)
-
-# Ensure that RELEASABLES and CLEANTARGETS cannot expand indefinitely in successive calls to this flm:
-CLEANTARGETS:=
-RELEASABLES:=
-
-# There is only one resource header (.rsg) file and we only
-# make that if we are asked.
-RSGDIR:=$(EPOCROOT)/epoc32/include
-ifneq ($(or $(HEADER),$(HEADERONLY)),)
-        RESOURCEHEADER:=$(RSGDIR)/$(HEADER)
-
-        # If there are multiple LANGUAGES then it is the last one in the list
-        # which produces the header.
-        HEADLANG:=$(lastword $(LANGUAGES:SC=sc))
-else
-	HEADLANG:=
-    RESOURCEHEADER:=
-endif
-
-# we create intermediate .rpp and .d files
-INTERBASE:=$(OUTPUTPATH)/$(TARGET_lower)$(if $(TARGETPATH),_$(subst /,_,$(TARGETPATH)),)
-
-################################## localisation ###########################$(GNUMKDIR)#############
-# Only make copies for full resource builds
-
-# Initialise to prevent RELEASABLES spill-over between calls
-DESTRPP:=
-INFOFILE:=
-
-ifeq ($(HEADERONLY),)
-
-RSSBASENAME:=$(call lowercase,$(basename $(notdir $(SOURCE))))
-DESTRPP:=$(EPOCROOT)/epoc32/localisation/$(RSSBASENAME)/rsc/$(RSSBASENAME).rpp
-$(call makepath,$(EPOCROOT)/epoc32/localisation/$(RSSBASENAME)/rsc)
-
-INFOFILE:=$(EPOCROOT)/epoc32/localisation/group/$(RSSBASENAME).info
-# If there are MULTIPLE languages then copy the .rpp for the last one
-RPPLANG:=$(lastword $(LANGUAGES:SC=sc))
-
-# Copy .rpp files from epoc32/build/ to epoc32/localisation/x/rsc/x.rpp and create .info files in localisation
-define CreateRppAndInfo
-
-ifeq ($(RESOURCE_$(call sanitise,$(SOURCE))),)
-RESOURCE_$(call sanitise,$(SOURCE)):=1
-
-RESOURCE:: $(DESTRPP) $(INFOFILE)
-
-$(DESTRPP): $(INTERBASE)_$(RPPLANG).rpp
-	$(call startrule,rppfilecopy,FORCESUCCESS) \
-	$(GNUCP) $$< $$@ \
-	$(call endrule,rppfilecopy)
-
-$(INFOFILE)::
-	@if [ ! -d $(EPOCROOT)/epoc32/localisation/group ]; then $(GNUMKDIR) -p $(EPOCROOT)/epoc32/localisation/group; fi
-	@if [ ! -f $$@ ]; then echo "DATADIR: /$(RSSBASENAME)" > $$@ ; fi
-	@echo -e "\n/z$(TARGETPATH)/$(TARGET_lower).rsc : $(RSSBASENAME).rpp" >> $$@
-
-CLEANTARGETS:=$$(CLEANTARGETS) $(DESTRPP) $(INFOFILE)
-
-endif
-endef
-
-$(eval $(call CreateRppAndInfo))
-endif
-################################# end of localisation ###################################
-
-# make the output directories while reading makefile - some build engines prefer this
-$(call makepath,$(INTERBASE))
-
-# common pre-processor options
-CPPOPT:=-nostdinc -undef -D_UNICODE -include $(PRODUCT_INCLUDE)\
- -I$(dir $(SOURCE)) $(foreach I, $(USERINCLUDE),-I$(I) ) -I- $(foreach J,$(SYSTEMINCLUDE),-I$(J) )
-
-CREATABLEPATHS:=$(RSCDIR) $(RSGDIR) $(OUTPUTPATH)
-
-# additional binary resource copies performed based on BINCOPYDIRS
-RSCCOPYDIRS:=
-ifneq ($(BINCOPYDIRS),)
-        RSCCOPYDIRS:=$(subst //,/,$(patsubst %,%/$(if $(TARGETPATH),/z/$(TARGETPATH),),$(BINCOPYDIRS)))
-        CREATABLEPATHS:=$(CREATABLEPATHS) $(RSCCOPYDIRS)
-endif
-
-###############################################################################
-define preprocessresource
-# $(1) is the RPPFILE		(eg. /epoc32/build/xxx/b_sc.rpp)
-# $(2) is the related RESOURCEFILE if any (eg. /a/b.rsc)
-# $(3) is the LANGUAGE		(eg. sc or 01 or 02 ...)
-
-  ifeq ($(TARGET_$(call sanitise,$1)),)
-    TARGET_$(call sanitise,$1):=1
-    $(if $(FLMDEBUG),$(info preprocessresource: $(1) for $(2) LANG:$(3)))
-
-    RESOURCE_DEPS:: $(1).d
-    $(1).d: $(SOURCE)
-	  $(call startrule,resourcedependencies,FORCESUCCESS) \
-	  $(GNUCPP) -C -DLANGUAGE_$(3) -DLANGUAGE_$(subst sc,SC,$(3)) $(call makemacrodef,-D,$(MMPDEFS))\
-	  $(CPPOPT) $(SOURCE) -M -MG -MT"$(1)" | \
-	  $(GNUSED)  -r 's# ([^ \/]+\.((rsg)|(mbg)))# $(EPOCROOT)\/epoc32\/include\/\1#ig' > $(1).d \
-	  $(call endrule,resourcedependencies)
-
-    $(1): $(1).d
-	  $(call startrule,resourcepreprocess,FORCESUCCESS) \
-	  $(GNUCPP) -C -DLANGUAGE_$(3) -DLANGUAGE_$(subst sc,SC,$(3)) $(call makemacrodef,-D,$(MMPDEFS))\
-	  $(CPPOPT) $(SOURCE) -o $$@ \
-	  $(call endrule,resourcepreprocess)
-
-    CLEANTARGETS:= $$(CLEANTARGETS) $(1)
-
-    $(eval DEPENDFILENAME:=$(1).d)
-    $(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
-
-    CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
-    ifneq "$(DEPENDFILE)" ""
-      ifeq "$(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS)))" ""
-        -include $(DEPENDFILE)
-      endif
-    endif
-
-  endif
-endef # preprocessresource #
-
-###############################################################################
-define copyresource
-# $(1) is the source
-# $(2) is the destination
-
-RELEASABLES:=$$(RELEASABLES) $(2)
-
-   ifeq ($(TARGET_$(call sanitise,$2)),)
-           TARGET_$(call sanitise,$2):=1
-        CLEANTARGETS:=$$(CLEANTARGETS) $2
-
-        RESOURCE:: $2
-        ## perform additional copies of binaries
-        #
-        # Only certain builds require further copies of the generated resource binaries
-        #
-        $(2): $(1)
-		$(call startrule,resourcecopy,FORCESUCCESS) \
-		$(GNUCP) $$< $$@ \
-		$(call endrule,resourcecopy)
-
-   endif
-
-endef # copyresource #
-
-###############################################################################
-define generateresource
-
-# $(1) is the resource filename e.g. /a/b/resource.rsc
-# $(2) is the preprocessed resource to make it from
-# $(3) is the language e.g. sc or 01 or 02
-
-    RELEASABLES:=$$(RELEASABLES) $(1)
-
-        ifeq ($(TARGET_$(call sanitise,$1)),)
-                TARGET_$(call sanitise,$1):=1
-            CLEANTARGETS:=$$(CLEANTARGETS) $(1)
-
-            $(if $(FLMDEBUG),$(info generateresource: $(1) from $(2) LANG:$(3)),)
-
-
-            RESOURCE:: $(1)
-
-            $(1): $(2) $(RCOMP)
-			$(call startrule,resourcecompile,FORCESUCCESS) \
-			$(RCOMP) -m045,046,047 -u -o$(1) -s$(2) \
-			$(call endrule,resourcecompile)
-
-        endif
-#	Whether or not we have generated this resource for some other variant, check if there
-#       are any new copies to be made for this variant. e.g. winscw requires that we make
-#       some extra copies.
-
-        $(foreach F,$(sort $(patsubst %,%/$(notdir $(1)),$(RSCCOPYDIRS))),$(call copyresource,$(1),$(F)))
-
-        # individual source file compilation
-        SOURCETARGET_$(call sanitise,$(SOURCE)): $(1)
-
-endef # generateresource
-
-
-###############################################################################
-define generateresourceheader
-# $(1) is the resource header	(eg. /epoc32/include/a.rsg)
-# $(2) is the preprocessed resource to make it from
-# $(3) is the language to use	(eg. sc)
-
-		RELEASABLES:= $$(RELEASABLES) $(1)
-
-        ifeq ($(TARGET_$(call sanitise,$1)),)
-                TARGET_$(call sanitise,$1):=1
-                CLEANTARGETS:= $$(CLEANTARGETS) $(1)
-                $(if $(FLMDEBUG),$(info resourceheader: $(1) from $(2) LANG:$(3)))
-
-                RESOURCE:: $(1)
-
-                $(1): $(2) $(RCOMP)
-			$(call startrule,resourceheader,FORCESUCCESS) \
-			$(RCOMP) -m045,046,047 -u -h$(1) -s$(2) \
-			$(call endrule,resourceheader)
-
-        endif
-
-
-        # individual source file compilation
-        SOURCETARGET_$(call sanitise,$(SOURCE)): $(1)
-
-endef
-
-###############################################################################
-## call the generator
-
-# We always create at least the header
-# even if we sometimes don't create the resources
-ifneq ($(RESOURCEHEADER),)
-        $(eval $(call generateresourceheader,$(RESOURCEHEADER),$(INTERBASE)_$(HEADLANG).rpp,$(HEADLANG)))
-endif
-
-ifeq ($(HEADERONLY),)
-        # generate a resource file for each language
-        # For sc we generate $(RESBASE).rsc and define LANGUAGE_SC and LANGUAGE_sc.
-        $(foreach L,$(LANGUAGES:SC=sc),$(eval $(call preprocessresource,$(INTERBASE)_$(L).rpp,$(RESBASE).r$(L),$(L))))
-        $(foreach L,$(LANGUAGES:SC=sc),$(eval $(call generateresource,$(RESBASE).r$(L),$(INTERBASE)_$(L).rpp,$(L))))
-else
-        # No resources are going to be made so unless we specifically ask for it, there will be no
-        # preprocessed file from which to create the header:
-
-        $(eval $(call preprocessresource,$(INTERBASE)_$(HEADLANG).rpp,,$(HEADLANG)))
-
-endif
-
-###############################################################################
-## .rfi generation in support of the gccxml build
-## Note that .rfi files are created from the dependency files generated from preprocessing resources to create .rpp files
-ifneq ($(RFIFILE),)
-  RESOURCE:: $(RFIFILE)
-  RELEASABLES:=$(RELEASABLES) $(RFIFILE)
-  CLEANTARGETS:=$(CLEANTARGETS) $(RFIFILE)
-  CREATABLEPATHS:=$(CREATABLEPATHS) $(dir $(RFIFILE))
-
-  RPPFILES:=$(foreach L,$(LANGUAGES:SC=sc),$(INTERBASE)_$(L).rpp)
-  $(eval $(call generaterfifile,$(RFIFILE),$(RPPFILES),$(addsuffix .d,$(RPPFILES))))
-endif
-
-
-## Clean up
-$(eval $(call GenerateStandardCleanTarget,$(CLEANTARGETS),$(CREATABLEPATHS),))
-# make the output directories while reading makefile - some build engines prefer this
-$(call makepath,$(CREATABLEPATHS))
-
-# for the abld -what target
-RELEASABLES:=$(RELEASABLES) $(DESTRPP) $(INFOFILE)
-$(eval $(call whatmacro,$(RELEASABLES),WHATRESOURCES))
-
+# 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:
+# Function Like Makefile (FLM) to create a resource header (.rsg)
+# and resource files (.rsc, .r01, .r02 etc.)
+#
+#
+
+## Parameters that are expected:
+# TARGET
+# TARGETPATH
+# LANGUAGES
+# HEADER
+# HEADERONLY
+# EPOCROOT
+# MMPDEFS
+# PRODUCT_INCLUDE
+# SYSTEMINCLUDE
+# USERINCLUDE
+# GNUCPP
+# GNUSED
+# RCOMP
+# OUTPUTPATH
+# SOURCE
+# BINCOPYDIRS
+
+
+# The rss is pre-processed once for each language and results
+# in a file with extension r$(LANGUAGE) where $(LANGUAGE) is
+# either "sc" or a 2 (or more) digit number.
+ifneq ($(TARGETPATH),)
+RSCDIR:=$(subst //,/,$(EPOCROOT)/epoc32/data/z/$(TARGETPATH))
+else
+RSCDIR:=$(subst //,/,$(EPOCROOT)/epoc32/data)
+endif
+RESBASE:=$(RSCDIR)/$(TARGET_lower)
+
+# Ensure that RELEASABLES and CLEANTARGETS cannot expand indefinitely in successive calls to this flm:
+CLEANTARGETS:=
+RELEASABLES:=
+CREATABLEPATHS:=
+
+# There is only one resource header (.rsg) file and we only
+# make that if we are asked.
+RSGDIR:=$(EPOCROOT)/epoc32/include
+# If there are multiple LANGUAGES then it is the last one in the list
+# which produces the header.
+HEADLANG:=$(lastword $(LANGUAGES:SC=sc))
+ifneq ($(or $(HEADER),$(HEADERONLY)),)
+        RESOURCEHEADER:=$(RSGDIR)/$(HEADER)
+
+else
+        RESOURCEHEADER:=
+endif
+
+# we create intermediate .rpp and .d files
+INTERBASE_TMP:=$(OUTPUTPATH)/$(TARGET_lower)_$(notdir $(basename $(SOURCE)))
+INTERBASE:=$(OUTPUTPATH)/$(TARGET_lower)
+
+
+# common pre-processor options
+
+# We really should be using -iquote with a recent cpp.  This is a note for when we do update:
+#CPPOPT:=-nostdinc -undef -Wno-trigraphs -D_UNICODE -include $(PRODUCT_INCLUDE)\
+# -I$(dir $(SOURCE)) $(foreach I, $(USERINCLUDE),-iquote $(I) ) $(foreach J,$(SYSTEMINCLUDE),-I $(J) )
+
+CPPOPT:=-nostdinc -undef -Wno-trigraphs -D_UNICODE -include $(PRODUCT_INCLUDE)\
+ -I$(dir $(SOURCE)) $(foreach I, $(USERINCLUDE),-I$(I) ) -I- $(foreach J,$(SYSTEMINCLUDE),-I$(J) )
+
+CREATABLEPATHS:=$(CREATABLEPATHS) $(RSCDIR) $(RSGDIR) $(OUTPUTPATH) 
+
+# We intend to generate the resource in an intermediate location and copy to the targetpath to
+# ensure that when the "same" resource is built into separare target paths, it doesn't have to be 
+# completely recreated each time - just copied.
+RSCCOPYDIRS:=$(RSCDIR)
+
+# additional binary resource copies performed based on BINCOPYDIRS
+ifneq ($(BINCOPYDIRS),)
+        RSCCOPYDIRS:=$(RSCCOPYDIRS) $(subst //,/,$(patsubst %,%/$(if $(TARGETPATH),/z/$(TARGETPATH),),$(BINCOPYDIRS)))
+endif
+CREATABLEPATHS:=$(CREATABLEPATHS) $(RSCCOPYDIRS)
+
+###############################################################################
+
+
+define preprocessresource
+# $(1) is the RPPFILE		(eg. /epoc32/build/xxx/b_sc.rpp)
+# $(2) is the related RESOURCEFILE if any (eg. /a/b.rsc)
+# $(3) is the LANGUAGE		(eg. sc or 01 or 02 ...)
+# $(4) is the "primary" language on which all the others depend
+
+  ifeq ($(TARGET_$(call sanitise,$1)),)
+    TARGET_$(call sanitise,$1):=1
+    $(if $(FLMDEBUG),$$(info <debug>preprocessresource: $(1) for $(2) LANG:$(3) dep $(4)</debug>))
+
+
+    # Correct dependency information when a header file can't be found.
+    # If the c preprocessor can't find a dependency it appears as it did in the #include statement
+    # e.g. "filename.mbg" or "filename.rsg" in the dependency file.
+
+ifneq ($(NO_DEPEND_GENERATE),)
+    # This version minimises the size of dependency files, to contain only .mbg and .rsg deps.
+    # It allows resources to be built in the right order but doesn't impose the weight of
+    # of full dependency information which can overwhelm make in large builds.
+    # The strategy is filter lines which don't have .rsg or .mbg dependencies in them and
+    # to sift each line to leave out non-relevant things like other header files, .hrh 
+    # files etc.  In the end don't print anything at all if we did not find the target.
+
+define  DEPENDENCY_CORRECTOR
+{ $(DEPCRUNCH) --extensions rsg,mbg --assume '$$$$(EPOCROOT)/epoc32/include' ; } 
+endef
+
+else
+    # This can correct the dependencies by assuming that the file will be in epoc32\include as this is the default
+    DEPENDENCY_CORRECTOR:=$(GNUSED)  -r 's% ([^ \/]+\.((rsg)|(mbg)))% $(EPOCROOT)\/epoc32\/include\/\1%ig' 
+endif
+
+
+    ifeq "$1" "$4"
+        RESOURCE_DEPS:: $1.d
+
+        $1.d: $(SOURCE)
+	  $(call startrule,resourcedependencies,FORCESUCCESS) \
+	  $(GNUCPP) -DLANGUAGE_$(3) -DLANGUAGE_$(subst sc,SC,$3) $(call makemacrodef,-D,$(MMPDEFS))\
+	  $(CPPOPT) $(SOURCE) -M -MG -MT"$1" | \
+	  $$(DEPENDENCY_CORRECTOR) >$$@ \
+	  $(call endrule,resourcedependencies)
+
+         $1 : $1.d
+
+    else
+         $1 : $4
+    endif
+
+    $1:
+	  $(call startrule,resourcepreprocess,FORCESUCCESS) \
+	  $(GNUCPP) -C -DLANGUAGE_$3 -DLANGUAGE_$(subst sc,SC,$(3)) $(call makemacrodef,-D,$(MMPDEFS))\
+	  $(CPPOPT) $(SOURCE) -o $$@ \
+	  $(call endrule,resourcepreprocess)
+    endif
+
+    CLEANTARGETS:= $$(CLEANTARGETS) $1
+
+    ifeq "$(MAKEFILE_GROUP)" "RESOURCE"
+    ifeq "$1" "$4"
+      $(eval DEPENDFILENAME:=$1.d)
+      $(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
+      
+      CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
+      ifneq "$(DEPENDFILE)" ""
+        ifeq "$(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS)))" ""
+          ifeq "$(MAKEFILE_GROUP)" "RESOURCE"
+           -include $(DEPENDFILE)
+          endif
+        endif
+      endif
+    endif
+
+  endif
+endef # preprocessresource #
+
+###############################################################################
+define copyresource
+# $(1) is the source
+# $(2) is the space separated list of destinations which must be filenames
+
+   RELEASABLES:=$$(RELEASABLES) $(2)
+
+   $(info <finalcopy source='$1'>$2</finalcopy>)
+ 
+endef # copyresource #
+
+###############################################################################
+define generateresource
+
+# $(1) is the resource filename e.g. /a/b/resource.rsc
+# $(2) is the preprocessed resource to make it from
+# $(3) is the language e.g. sc or 01 or 02
+
+
+        ifeq ($(TARGET_$(call sanitise,$1)),)
+                TARGET_$(call sanitise,$1):=1
+
+            $(if $(FLMDEBUG),$(info <debug>generateresource: $(1) from $(2) LANG:$(3)</debug>),)	
+            $(if $(FLMDEBUG),$(info <debug>generateresource: copies: $(sort $(patsubst %,%/$(notdir $(1)),$(RSCCOPYDIRS)))</debug>))
+
+            CLEANTARGETS:=$$(CLEANTARGETS) $(1)
+
+            RESOURCE:: $(1)
+
+            $(1): $(2) $(RCOMP)
+			$(call startrule,resourcecompile,FORCESUCCESS) \
+			$(RCOMP) -m045,046,047 -u -o$(1) -s$(2)  \
+			$(call endrule,resourcecompile)
+
+        endif
+
+#	Whether or not we have generated this resource for some other variant, check if there
+#       are any new copies to be made for this variant. e.g. winscw requires that we make
+#       some extra copies.  We tried to copy after running rcomp itself but we still need these
+#       targets for the sake of dependencies or, for example, if someone merely adds a new copy 
+#       when the resource is up-to-date
+
+        $(call copyresource,$1,$(sort $(patsubst %,%/$(notdir $1),$(RSCCOPYDIRS))))
+
+
+        # individual source file compilation
+        SOURCETARGET_$(call sanitise,$(SOURCE)): $(1)
+
+endef # generateresource
+
+
+###############################################################################
+define generateresourceheader
+# $(1) is the resource header	(eg. /epoc32/include/a.rsg)
+# $(2) is the preprocessed resource to make it from
+# $(3) is the language to use	(eg. sc)
+
+        RELEASABLES:= $$(RELEASABLES) $(1)
+
+        ifeq ($(TARGET_$(call sanitise,$1)),)
+                TARGET_$(call sanitise,$1):=1
+                $(if $(FLMDEBUG),$(info <debug>resourceheader: $(1) from $(2) LANG:$(3)</debug>))
+
+                RESOURCE:: $(1)
+
+                $(1): $(2) $(RCOMP)
+			$(call startrule,resourceheader,FORCESUCCESS) \
+			$(RCOMP) -m045,046,047 -u -h$(1) -s$(2) \
+			$(call endrule,resourceheader)
+
+        endif
+
+
+        # individual source file compilation
+        SOURCETARGET_$(call sanitise,$(SOURCE)): $(1)
+
+endef
+
+###############################################################################
+## call the generator
+
+# We always create at least the header
+# even if we sometimes don't create the resources
+ifneq ($(RESOURCEHEADER),)
+        $(eval $(call generateresourceheader,$(RESOURCEHEADER),$(INTERBASE_TMP)_$(HEADLANG).rpp,$(HEADLANG)))
+endif
+
+# The one on which the others will depend i.e. they will 
+# "sit in it's dependency slipstream" or in other words
+# We only have to make one dependency file because all of
+# the other languages will benefit from the dependency file
+# belonging to this language.
+PRIMARYRPPFILE:=$(INTERBASE_TMP)_$(HEADLANG).rpp
+ifeq ($(HEADERONLY),)
+        # generate a resource file for each language
+        # For sc we generate $(RESBASE).rsc and define LANGUAGE_SC and LANGUAGE_sc.
+        $(foreach L,$(LANGUAGES:SC=sc),$(eval $(call preprocessresource,$(INTERBASE_TMP)_$(L).rpp,$(INTERBASE).r$(L),$(L),$(PRIMARYRPPFILE))))
+
+        ifeq "$(MAKEFILE_GROUP)" "RESOURCE"
+            $(foreach L,$(LANGUAGES:SC=sc),$(eval $(call generateresource,$(INTERBASE).r$(L),$(INTERBASE_TMP)_$(L).rpp,$(L))))
+        endif
+else
+        # No resources are going to be made so unless we specifically ask for it, there will be no
+        # preprocessed file from which to create the header:
+
+        $(eval $(call preprocessresource,$(INTERBASE_TMP)_$(HEADLANG).rpp,,$(HEADLANG),$(PRIMARYRPPFILE)))
+
+endif
+
+###############################################################################
+## .rfi generation in support of the gccxml build
+## Note that .rfi files are created from the dependency files generated from preprocessing resources to create .rpp files
+ifneq ($(RFIFILE),)
+  RESOURCE:: $(RFIFILE)
+  RELEASABLES:=$(RELEASABLES) $(RFIFILE)
+  CREATABLEPATHS:=$(CREATABLEPATHS) $(dir $(RFIFILE))/
+
+  RPPFILES:=$(foreach L,$(LANGUAGES:SC=sc),$(INTERBASE_TMP)_$(L).rpp)
+  $(eval $(call generaterfifile,$(RFIFILE),$(RPPFILES),$(PRIMARYRPPFILE).d))
+endif
+
+
+## Clean up
+$(call raptor_clean,$(CLEANTARGETS))
+# make the output directories while reading makefile - some build engines prefer this
+$(call makepath,$(CREATABLEPATHS))
+
+# for the --what option and the log file
+RELEASABLES:=$(RELEASABLES) $(DESTRPP) $(INFOFILE)
+$(call raptor_release,$(RELEASABLES),RESOURCE)
+
--- a/sbsv2/raptor/lib/flm/romfile.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/romfile.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,42 +1,42 @@
-# romfile.mk
-#
-# Copyright (c) 2008 : Symbian Software Limited. All rights reserved.
-#
-# define macros that are needed by romfile creation
-
-define DoRomSet
-
-ifeq ($(call uppercase,$(TARGETTYPE)),LIB)
-BUILDROMTARGET:=
-endif
-
-ifeq ($(call uppercase,$(TARGETTYPE)),KEXT)
-ROMFILETYPE:=extension[MAGIC]
-ABIDIR:=KMAIN
-endif
-ifeq ($(call uppercase,$(TARGETTYPE)),LDD)
-ROMFILETYPE:=device[MAGIC]
-ABIDIR:=KMAIN
-endif
-ifeq ($(call uppercase,$(TARGETTYPE)),PDD)
-ROMFILETYPE:=device[MAGIC]
-ABIDIR:=KMAIN
-endif
-ifeq ($(call uppercase,$(TARGETTYPE)),VAR)
-ROMFILETYPE:=variant[MAGIC]
-ABIDIR:=KMAIN
-endif
-ifeq ($(call uppercase,$(TARGETTYPE)),KDLL)
-ABIDIR:=KMAIN
-endif
-
-ifneq ($(CALLDLLENTRYPOINTS),)
-ROMFILETYPE:=dll
-endif
-ifeq ($(ROMFILETYPE),primary)
-ABIDIR:=KMAIN
-endif
-
-endef
-
-
+# romfile.mk
+#
+# Copyright (c) 2008 : Symbian Software Limited. All rights reserved.
+#
+# define macros that are needed by romfile creation
+
+define DoRomSet
+
+ifeq ($(call uppercase,$(TARGETTYPE)),LIB)
+BUILDROMTARGET:=
+endif
+
+ifeq ($(call uppercase,$(TARGETTYPE)),KEXT)
+ROMFILETYPE:=extension[MAGIC]
+ABIDIR:=KMAIN
+endif
+ifeq ($(call uppercase,$(TARGETTYPE)),LDD)
+ROMFILETYPE:=device[MAGIC]
+ABIDIR:=KMAIN
+endif
+ifeq ($(call uppercase,$(TARGETTYPE)),PDD)
+ROMFILETYPE:=device[MAGIC]
+ABIDIR:=KMAIN
+endif
+ifeq ($(call uppercase,$(TARGETTYPE)),VAR)
+ROMFILETYPE:=variant[MAGIC]
+ABIDIR:=KMAIN
+endif
+ifeq ($(call uppercase,$(TARGETTYPE)),KDLL)
+ABIDIR:=KMAIN
+endif
+
+ifneq ($(CALLDLLENTRYPOINTS),)
+ROMFILETYPE:=dll
+endif
+ifeq ($(ROMFILETYPE),primary)
+ABIDIR:=KMAIN
+endif
+
+endef
+
+
--- a/sbsv2/raptor/lib/flm/stack.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/stack.mk	Wed Jun 23 16:56:47 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: 
-# # Implements a stack mechanism for FLMS
-# # Author: Timothy Murphy
-# # CHANGE THIS FILE AT YOUR PERIL! :-)
-# # It is very sensitive to spaces on the end of variables.
-# # It took a lot of trouble to get this exactly right so 
-# # be careful about changing it.
-# # A "call stack" is necessary for variables which are used
-# # in an append-manner by glue makefiles.  This behavior
-# # is only needed where and FLM call has the form:
-# # 	OUTPUTPATH:=$(OUTPUTPATH)/subdir
-# #	include $(FLMHOME)/exefile.flm
-# # This is because the outputpath setting must be undone
-# # before the next call to an FLM that uses OUTPUTPATH (otherwise it keeps growing)
-# # USAGE:
-# # $(call vsave,VARIABLE1 VARIABLE2)
-# # $(call vrestore)
-#
-
-ifeq ($(VARIABLE_STACK_NAME),)
-VARIABLE_STACK_NAME:=STACK
-endif
-# $(1) should list the variables 
-
-# vadd must be exactly of the form of 3 lines, the middle one containing "$(1)"
-# Otherwise the extra return will be treated like a character rather than as whitespace
-
-define LINEFEED
-
-
-endef
-
-define vadd
-$(1):=$(2)
-
-endef
-
-#
-# Create a kind of stack "frame"
-# The parameters are names of variables whose values are to be stored in the frame
-# so that these values may be restored later.
-#
-# use thus:
-# $(call vsave,OUTPUTPATH SOURCEPATH CDEFS)
-#
-define vsave
-$(eval 
-VARIABLE_STACK_NAME:=$(VARIABLE_STACK_NAME).F
-$$(VARIABLE_STACK_NAME):=$$(foreach VAR,$(1),$$(call vadd,$$(VAR),$$($$(VAR)))))
-endef
-
-#
-# Pop the top stack frame.
-#
-# use thus:
-# $(call vrestore)
-#
-define vrestore
-$(eval $($(VARIABLE_STACK_NAME))
-VARIABLE_STACK_NAME:=$(patsubst %.F,%,$(VARIABLE_STACK_NAME))
-)
-endef
-
+#
+# 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: 
+# # Implements a stack mechanism for FLMS
+# # Author: Timothy Murphy
+# # CHANGE THIS FILE AT YOUR PERIL! :-)
+# # It is very sensitive to spaces on the end of variables.
+# # It took a lot of trouble to get this exactly right so 
+# # be careful about changing it.
+# # A "call stack" is necessary for variables which are used
+# # in an append-manner by glue makefiles.  This behavior
+# # is only needed where and FLM call has the form:
+# # 	OUTPUTPATH:=$(OUTPUTPATH)/subdir
+# #	include $(FLMHOME)/exefile.flm
+# # This is because the outputpath setting must be undone
+# # before the next call to an FLM that uses OUTPUTPATH (otherwise it keeps growing)
+# # USAGE:
+# # $(call vsave,VARIABLE1 VARIABLE2)
+# # $(call vrestore)
+#
+
+ifeq ($(VARIABLE_STACK_NAME),)
+VARIABLE_STACK_NAME:=STACK
+endif
+# $(1) should list the variables 
+
+# vadd must be exactly of the form of 3 lines, the middle one containing "$(1)"
+# Otherwise the extra return will be treated like a character rather than as whitespace
+
+define LINEFEED
+
+
+endef
+
+define vadd
+$(1):=$(2)
+
+endef
+
+#
+# Create a kind of stack "frame"
+# The parameters are names of variables whose values are to be stored in the frame
+# so that these values may be restored later.
+#
+# use thus:
+# $(call vsave,OUTPUTPATH SOURCEPATH CDEFS)
+#
+define vsave
+$(eval 
+VARIABLE_STACK_NAME:=$(VARIABLE_STACK_NAME).F
+$$(VARIABLE_STACK_NAME):=$$(foreach VAR,$(1),$$(call vadd,$$(VAR),$$($$(VAR)))))
+endef
+
+#
+# Pop the top stack frame.
+#
+# use thus:
+# $(call vrestore)
+#
+define vrestore
+$(eval $($(VARIABLE_STACK_NAME))
+VARIABLE_STACK_NAME:=$(patsubst %.F,%,$(VARIABLE_STACK_NAME))
+)
+endef
+
--- a/sbsv2/raptor/lib/flm/standard.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/standard.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,260 +1,274 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<interface name="Symbian.mmp" extends="base.flm" abstract="true">
-		<param name='AAPCS_OPTION'/>
-		<param name='ALWAYS_BUILD_AS_ARM' default=''/>
-		<param name='SET_ARMINC' default=''/>
-		<param name='ARMLIBS' default=''/>
-		<param name='ARMFPU' default='softvfp'/>
-		<param name='POSTLINKFPU' default='softvfp'/>
-		<param name='ARMRT' default=''/>
-		<param name='TESTPATH' default=''/>
-		<param name='CAPABILITY'/>
-		<param name='CPPONLYOPTION' default='-E'/>
-		<param name='LIBRARY'/>
-		<param name='LIBRARY_DEBUG'/>
-		<param name='LINKAS' default=''/>
-		<param name='STATICLIBRARY' default=''/>
-		<param name='NOEXPORTLIBRARY' default=''/>
-		<param name='EXPORTLIBRARY' default=''/>
-		<param name='EXPORTUNFROZEN' default=''/>
-		<param name='FEEDBACK_OPTION' default='--feedback=' />
-		<param name='FIRSTLIB' default=''/>
-		<param name='LINKEROPTION_ARMCC' default=''/>
-		<param name='LISTING_OPTION' default='-S'/>
-		<param name='MMPDEFS' default=''/>
-		<param name='NOCOMPRESSTARGET' default=''/>
-		<param name='POSTLINKER_SUPPORTS_WDP' default=''/>
-		<param name='PAGED' default=''/>
-		<param name='PAGEDCODE_OPTION' default='default'/>
-		<param name='PAGEDDATA_OPTION' default='default'/>
-		<param name='PRODUCT_INCLUDE'/>
-		<param name='REQUESTEDTARGETEXT' default=''/>
-		<param name='GENERATELINKERFEEDBACK' default=''/>
-		<param name='LINKERFEEDBACK_STAGE2' default='' />
-		<param name='MULTIFILE_ENABLED' default=''/>
-		<param name='SYSTEMINCLUDE'/>
-		<param name='SECUREID' default=''/>
-		<param name='SOURCE' default=''/>
-		<param name='TARGET'/>
-		<param name='TARGET_lower'/>
-		<param name='LTCG' default=''/>
-		<param name='LTCG_OPTION' default='--ltcg'/>
-		<param name='TARGETTYPE'/>
-		<!-- UID2 and 3 must be empty by default or def file name generation is affected -->
-		<param name='UID2' default=''/>
-		<param name='UID3' default=''/>
-		<param name='VENDORID' default=''/>
-		<param name='USERINCLUDE'/>
-		<param name='OPTION_ARMCC' default=''/>
-		<param name='OPTION_REPLACE_ARMCC' default=''/>
-		<param name='DEBUGLIBRARY' default=''/>
-		<param name='DEFFILE'/>
-		<param name='DEBUGGABLE' default=''/>
-		<param name='DEFFILEKEYWORD' default=''/>
-		<param name='EPOCHEAPSIZEMIN' default=''/>
-		<param name='EPOCHEAPSIZEMAX' default=''/>
-		<param name='EPOCPROCESSPRIORITY' default=''/>
-		<param name='EPOCSTACKSIZE' default=''/>
-		<param name='EPOCFIXEDPROCESS' default=''/>
-		<param name='EPOCALLOWDLLDATA' default=''/>
-		<param name='PLATMACROS.WINDOWS' default=''/>
-		<param name='PLATMACROS.LINUX' default=''/>
-		<param name='MAKEDEFFILE' default='1'/>
-		<param name='STDCPP' default=''/>
-		<param name='NOSTDCPP' default=''/>
-		<param name='NEWLIB' default=''/>
-		<param name='SMPSAFE' default=''/>
-		<param name='STDCPP_INCLUDE' default=''/>
-		<param name='ROMTARGET' default=''/>
-		<param name='RAMTARGET' default=''/>
-		<param name='CC.OPT.SOFTVFP_MAYBE_VFPV2' default=''/>
-		<param name='CC.VAL.SOFTVFP_MAYBE_VFPV2' default=''/>
-		<param name='CODE_SEGMENT_START' default=''/>
-		<param name='TOOLCHAIN' default=''/>
-		<param name='TOOLCHAINVERSION' default=''/>
-	</interface>
-	<interface name="Symbian.e32abiv2" extends="Symbian.mmp" flm="e32abiv2.flm">
-		<param name='SUPPORTS_STDCPP_NEWLIB' default='1'/>
-		<param name='HAS_DEDICATED_OP_NEWDEL_LIB' default='1'/>
-		<param name='DEFAULT_STDCPP_NEWLIB'/>
-		<param name='DEFAULT_SYMBIAN_NEWLIB'/>
-		<param name='CHECKLIB'/>
-		<param name='ASM'/>
-		<param name='ASM_OUTPUT_OPTION'/>
-		<param name='ARM_INSTRUCTION_SET'/>
-		<param name='THUMB_INSTRUCTION_SET'/>
-		<param name='CC'/>
-		<param name='CC_ERRORS_CONTROL_OPTION'/>
-		<param name='CC_WARNINGS_CONTROL_OPTION'/>
-		<param name='CDEFS'/>
-		<param name='CIADEFS'/>
-		<param name='CFLAGS'/>
-		<param name='COMMANDFILE_OPTION'/>
-		<param name='COMPILE_ONLY_OPTION'/>
-		<param name='COMPILER_CIA_FLAGS'/>
-		<param name='COMPILER_FPU_FLAGS'/>
-		<param name='COMPILER_INTERWORK_DEFINES'/>
-		<param name='COMPILER_SYSTEM_INCLUDE_OPTION'/>
-		<param name='COMPILER_THUMB_DEFINES'/>
-		<param name='C_LANG_OPTION'/>		
-		<param name='CPP_LANG_OPTION'/>
-		<param name='CPPFILT'/>
-		<param name='CREATEVMAP'/>
-		<param name='CREATEVMAPCPP'/>
-		<param name='DEBUG_FORMAT'/>
-		<param name='DEBUG_INFO'/>
-		<param name='DEPEND_OPTION'/>
-		<param name='DEPEND_SKIP' default=''/>
-		<param name='ELF2E32'/>
-		<param name='EFREEZE'/>
-		<param name='EFREEZE_REMOVE_OPTION' default=''/>
-		<param name='ENUM_OPTION'/>
-		<param name='EXCEPTIONS'/>
-		<param name='NO_EXCEPTIONS'/>
-		<param name='EXPORT_VTBL_OPTION'/>
-		<param name='FEATURELISTFILES' default=''/>
-		<param name='FEATUREVARIANT' default=''/>
-		<param name='FEATUREVARIANTNAME' default=''/>
-		<param name='FPMODE_OPTION'/>
-		<param name='FROMELF'/>
-		<param name='FULLVARIANTPATH'/>
-		<param name='GENERATE_ABIV1_IMPLIBS' default=''/>		
-		<param name='RVCT3_1' default=''/>
-		<param name='LD'/>
-		<param name='LD_ERRORS_CONTROL_OPTION'/>
-		<param name='LD_WARNINGS_CONTROL_OPTION'/>
-		<param name='LIBPATH'/>
-		<param name='LICENSERETRY_OPTION' default=''/>
-		<param name='LINKER_ADD_STATIC_RUNTIME'/>
-		<param name='LINKER_DEBUG_OPTION'/>
-		<param name='LINKER_DEFAULT_LIBS'/>
-		<param name='LINKER_DEFAULT_LIB_PATHS'/>
-		<param name='LINKER_ENTRY_OPTION'/>
-		<param name='LINKER_GROUP_START_OPTION'/>
-		<param name='LINKER_GROUP_END_OPTION'/>
-		<param name='LINKER_MISC_FLAGS'/>		
-		<param name='LINKER_NODEBUG_OPTION'/>
-		<param name='LINKER_SYMBOLS_FILE_OPTION'/>
-		<param name='LINKER_SYMBOLS_OPTION'/>
-		<param name='NEED_ENTRYPOINT_LIBRARY'/>
-		<param name='OUTPUT_OPTION' default='-o'/>
-		<param name='OUTPUTPATH'/>
-		<param name='OWN_LIBRARY_OPTION'/>
-		<param name='PERL'/>
-		<param name='PERTURBSTARTTIME'/>
-		<param name='PERTURBMSECS' default='500'/>
-		<param name='PREPDEF'/>
-		<param name='PREINCLUDE'/>
-		<param name='PREINCLUDE_OPTION'/>
-		<param name='PREPROCESSOR_OPTION'/>
-		<param name='RANSLEEP'/>
-		<param name='RELEASEPATH'/>
-		<param name='RESOLVED_DEFFILE'/>
-		<param name='RUNTIME_LIBS_LIST'/>
-		<param name='RUNTIME_LIBS_PATH'/>
-		<param name='RUNTIME_SYMBOL_VISIBILITY_OPTION'/>
-		<param name='NO_UNALIGNED_ACCESS' default=''/>
-		<param name='RVCTBIN'/>
-		<param name='RVCTINC'/>
-		<param name='RVCTLIB'/>
-		<param name='RW_BASE_OPTION'/>
-		<param name='SBSV1MAKE'/>
-		<param name='NMAKE'/>
-		<param name='NMAKEFLAGS'/>
-		<param name='SHARED_OBJECT_OPTION'/>
-		<param name='SO_NAME_OPTION'/>
-		<param name='SPLIT_OPTION'/>
-		<param name='KERNEL_STATIC_RUNTIME_LIB'/>
-		<param name='USER_STATIC_RUNTIME_LIB'/>
-		<param name='STATIC_LIBS_LIST'/>
-		<param name='STATIC_LIBS_PATH'/>
-		<param name='STATIC_LIBRARY_DIR'/>
-		<param name='STATIC_RUNTIME_DIR'/>
-		<param name='SYMBIAN_CCFLAGS'/>
-		<param name='SYMBIAN_LD_MESSAGE_OPTION'/>
-		<param name='SYMBIAN_LINK_FLAGS'/>
-		<param name='SYMVER_OPTION'/>
-		<param name='TARGET_ARCH_OPTION'/>
-		<param name='LINKER_ARCH_OPTION'/>
-		<param name='TESTCODE' default=''/>
-		<param name='TEST_OPTION' default=''/>
-		<param name='TRANSFORM_CIA'/>
-		<param name='USE_TRACE_COMPILER' default=''/>
-		<param name='TRANASM'/>
-		<param name='INSTRUCTION_SET'/>
-		<param name='MODULE'/>
-		<param name='USER_LIBS_PATH_OPTION'/>
-		<param name='VARIANTPLATFORM'/>
-		<param name='PLATFORM' default='$(VARIANTPLATFORM)'/>
-		<param name='VARIANTTYPE'/>
-		<param name='VERSION' default='10.0'/>
-		<param name='VERSIONHEX' default='000a0000'/>
-		<param name='VFE_OPTION'/>
-		<param name='EXPLICITVERSION' default=''/>
-	</interface>
-	<interface name="Symbian.exe" extends="Symbian.e32abiv2" flm="e32abiv2exe.flm">
-		<param name='TARGETTYPE' default="exe"/>
-		<param name='UID1' default="1000007a"/>
-	</interface>
-	<interface name="Symbian.stdexe" extends="Symbian.e32abiv2" flm="e32abiv2stdexe.flm">
-		<param name='TARGETTYPE' default="stdexe"/>
-		<param name='UID1' default="1000007a"/>
-		<param name='UID2' default="20004c45"/>
-		<param name='WCHARENTRYPOINT' default=""/>
-	</interface>
-	<interface name="Symbian.dll" extends="Symbian.e32abiv2" flm="e32abiv2dll.flm">
-		<param name='TARGETTYPE' default="dll"/>
-		<param name='UID1' default="10000079"/>
-	</interface>
-	<interface name="Symbian.stddll" extends="Symbian.e32abiv2" flm="e32abiv2stddll.flm">
-		<param name='TARGETTYPE' default="stddll"/>
-		<param name='UID1' default="10000079"/>
-		<param name='UID2' default="20004c45"/>
-	</interface>
-	<interface name="Symbian.lib" extends="Symbian.e32abiv2" flm="e32abiv2lib.flm">
-		<param name='AR'/>
-		<param name='ARCHIVER_CREATE_OPTION'/>
-		<param name='TARGETTYPE' default="lib"/>
-	</interface>
-	<interface name="Symbian.stdlib" extends="Symbian.lib" flm="e32abiv2stdlib.flm">
-		<param name='TARGETTYPE' default="stdlib"/>
-	</interface>
-	<interface name="Symbian.extension" extends="base.extension" flm="template_ext.flm">
-		<param name='RVCTBIN'/>
-		<param name='RVCTLIB'/>
-		<param name='RVCTINC'/>
-	</interface>
-	<interface name="Symbian.ani" extends="Symbian.dll" flm="e32abiv2ani.flm">
-	</interface>
-	<interface name="Symbian.plugin" extends="Symbian.dll" flm="e32abiv2plugin.flm">
-	</interface>
-	<interface name="Symbian.textnotifier2" extends="Symbian.dll" flm="e32abiv2textnotifier2.flm">
-	</interface>
-	<interface name="Symbian.implib" extends="Symbian.dll" flm="e32abiv2implib.flm">
-	</interface>
-	<interface name="Symbian.var" extends="Symbian.dll" flm="e32abiv2var.flm">
-	</interface>
-	<interface name="Symbian.var2" extends="Symbian.dll" flm="e32abiv2var2.flm">
-	</interface>
-	<interface name="Symbian.exexp" extends="Symbian.exe" flm="e32abiv2exexp.flm">
-	</interface>
-	<interface name="Symbian.kexe" extends="Symbian.exe" flm="e32abiv2kexe.flm">
-	</interface>
-	<interface name="Symbian.kdll" extends="Symbian.dll" flm="e32abiv2kdll.flm">
-	</interface>
-	<interface name="Symbian.kext" extends="Symbian.dll" flm="e32abiv2kext.flm">
-	</interface>
-	<interface name="Symbian.klib" extends="Symbian.lib" flm="e32abiv2klib.flm">
-	</interface>
-	<interface name="Symbian.ldd" extends="Symbian.dll" flm="e32abiv2ldd.flm">
-	</interface>
-	<interface name="Symbian.pdd" extends="Symbian.dll" flm="e32abiv2pdd.flm">
-	</interface>
-	<interface name="Symbian.pdl" extends="Symbian.dll" flm="e32abiv2pdl.flm">
-	</interface>
-	<interface name="Symbian.fsy" extends="Symbian.dll" flm="e32abiv2fsy.flm">
-	</interface>
-	<interface name="Symbian.none" extends="Symbian.mmp" flm="none.flm">
-	</interface>
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<interface name="Symbian.mmp" extends="base.flm" abstract="true">
+		<param name='AAPCS_OPTION'/>
+		<param name='ALWAYS_BUILD_AS_ARM' default=''/>
+		<param name='SET_ARMINC' default=''/>
+		<param name='ARMLIBS' default=''/>
+		<param name='ARMFPU' default=''/>
+		<param name='ARMRT' default=''/>
+		<param name='BYTEPAIRCOMPRESSTARGET' default=''/>
+		<param name='TESTPATH' default=''/>
+		<param name='CAPABILITY'/>
+		<param name='COMPRESSTARGET' default=''/>
+		<param name='CPPONLYOPTION' default='-E'/>
+		<param name='LIBRARY'/>
+		<param name='LIBRARY_DEBUG'/>
+		<param name='LINKAS' default=''/>
+		<param name='STATICLIBRARY' default=''/>
+		<param name='NOEXPORTLIBRARY' default=''/>
+		<param name='EXPORTLIBRARY' default=''/>
+		<param name='EXPORTUNFROZEN' default=''/>
+		<param name='FEEDBACK_OPTION' default='--feedback=' />
+		<param name='FIRSTLIB' default=''/>
+		<param name='INFLATECOMPRESSTARGET' default=''/>
+		<param name='LINKEROPTION_ARMCC' default=''/>
+		<param name='LISTING_OPTION' default='-S'/>
+		<param name='MMPDEFS' default=''/>
+		<param name='NOCOMPRESSTARGET' default=''/>
+		<param name='POSTLINKER_SUPPORTS_WDP' default=''/>
+		<param name='PAGED' default=''/>
+		<param name='PAGEDCODE_OPTION' default='default'/>
+		<param name='PAGEDDATA_OPTION' default='default'/>
+		<param name='PRODUCT_INCLUDE'/>
+		<param name='REQUESTEDTARGETEXT' default=''/>
+		<param name='GENERATELINKERFEEDBACK' default=''/>
+		<param name='LINKERFEEDBACK_STAGE2' default='' />
+		<param name='MULTIFILE_ENABLED' default=''/>
+		<param name='SYSTEMINCLUDE'/>
+		<param name='SECUREID' default=''/>
+		<param name='SOURCE' default=''/>
+		<param name='TARGET'/>
+		<param name='TARGET_lower'/>
+		<param name='LTCG' default=''/>
+		<param name='LTCG_OPTION' default='--ltcg'/>
+		<param name='TARGETTYPE'/>
+		<!-- UID2 and 3 must be empty by default or def file name generation is affected -->
+		<param name='UID2' default=''/>
+		<param name='UID3' default=''/>
+		<param name='VENDORID' default=''/>
+		<param name='USERINCLUDE'/>
+		<param name='OPTION_ARMCC' default=''/>
+		<param name='OPTION_REPLACE_ARMCC' default=''/>
+		<param name='DEBUGLIBRARY' default=''/>
+		<param name='DEFFILE'/>
+		<param name='DEBUGGABLE' default=''/>
+		<param name='DEFFILEKEYWORD' default=''/>
+		<param name='EPOCHEAPSIZEMIN' default=''/>
+		<param name='EPOCHEAPSIZEMAX' default=''/>
+		<param name='EPOCPROCESSPRIORITY' default=''/>
+		<param name='EPOCSTACKSIZE' default=''/>
+		<param name='EPOCFIXEDPROCESS' default=''/>
+		<param name='EPOCALLOWDLLDATA' default=''/>
+		<param name='EPOCNESTEDEXCEPTIONS' default=''/>
+		<param name='PLATMACROS.WINDOWS' default=''/>
+		<param name='PLATMACROS.LINUX' default=''/>
+		<param name='STDCPP' default=''/>
+		<param name='NOSTDCPP' default=''/>
+		<param name='NEWLIB' default=''/>
+		<param name='SMPSAFE' default=''/>
+		<param name='STDCPP_INCLUDE' default=''/>
+		<param name='ROMTARGET' default=''/>
+		<param name='RAMTARGET' default=''/>
+		<param name='CC.OPT.SOFTVFP_MAYBE_VFPV2' default=''/>
+		<param name='CC.VAL.SOFTVFP_MAYBE_VFPV2' default=''/>
+		<param name='CODE_SEGMENT_START' default=''/>
+		<param name='TOOLCHAIN' default=''/>
+		<param name='USE_RVCT22_DELETE_WORKAROUND' default=''/>
+	</interface>
+	<interface name="Symbian.e32abiv2" extends="Symbian.mmp" flm="e32abiv2.flm">
+		<param name='SUPPORTS_STDCPP_NEWLIB' default='1'/>
+		<param name='HAS_DEDICATED_OP_NEWDEL_LIB' default='1'/>
+		<param name='DEFAULT_STDCPP_NEWLIB'/>
+		<param name='DEFAULT_SYMBIAN_NEWLIB'/>
+		<param name='CHECKLIB'/>
+		<param name='ASM'/>
+		<param name='ASM_OUTPUT_OPTION'/>
+		<param name='ARM_INSTRUCTION_SET'/>
+		<param name='THUMB_INSTRUCTION_SET'/>
+		<param name='CC'/>
+		<param name='CC_ERRORS_CONTROL_OPTION'/>
+		<param name='CC_WARNINGS_CONTROL_OPTION'/>
+		<param name='CDEFS'/>
+		<param name='CIADEFS'/>
+		<param name='CFLAGS'/>
+		<param name='COMMANDFILE_OPTION'/>
+		<param name='COMPILE_ONLY_OPTION'/>
+		<param name='COMPILER_FPU_DEFAULT'/>
+		<param name='COMPILER_FPU_OPTION'/>
+		<param name='COMPILER_CIA_FLAGS'/>
+		<param name='COMPILER_INTERWORK_DEFINES'/>
+		<param name='COMPILER_SYSTEM_INCLUDE_OPTION'/>
+		<param name='COMPILER_THUMB_DEFINES'/>
+		<param name='C_LANG_OPTION'/>		
+		<param name='CPP_LANG_OPTION'/>
+		<param name='CPPFILT'/>
+		<param name='CREATEVMAP'/>
+		<param name='CREATEVMAPCPP'/>
+		<param name='DEBUG_FORMAT'/>
+		<param name='DEBUG_INFO'/>
+		<param name='DEPEND_OPTION'/>
+		<param name='ELF2E32'/>
+		<param name='EFREEZE'/>
+		<param name='EFREEZE_REMOVE_OPTION' default=''/>
+		<param name='ENUM_OPTION'/>
+		<param name='EXCEPTIONS'/>
+		<param name='NO_EXCEPTIONS'/>
+		<param name='EXPORT_VTBL_OPTION'/>
+		<param name='FEATURELISTFILES' default=''/>
+		<param name='FEATUREVARIANT' default=''/>
+		<param name='FEATUREVARIANTNAME' default=''/>
+		<param name='FEATUREVARIANTSAFE' default=''/>
+		<param name='FPMODE_OPTION'/>
+		<param name='FROMELF'/>
+		<param name='FULLVARIANTPATH'/>
+		<param name='RVCT3_1' default=''/>
+		<param name='LD'/>
+		<param name='LD_ERRORS_CONTROL_OPTION'/>
+		<param name='LD_WARNINGS_CONTROL_OPTION'/>
+		<param name='LD_WARNINGS_SUPPRESSION_ARMLIBS' default='' />
+		<param name='LIBPATH'/>
+		<param name='LICENSERETRY_OPTION' default=''/>
+		<param name='LINKER_ADD_STATIC_RUNTIME'/>
+		<param name='LINKER_DEBUG_OPTION'/>
+		<param name='LINKER_DEFAULT_LIBS'/>
+		<param name='LINKER_DEFAULT_LIB_PATHS'/>
+		<param name='LINKER_ENTRY_OPTION'/>
+		<param name='LINKER_GROUP_START_OPTION'/>
+		<param name='LINKER_GROUP_END_OPTION'/>
+		<param name='LINKER_MISC_FLAGS'/>		
+		<param name='LINKER_NODEBUG_OPTION'/>
+		<param name='LINKER_SYMBOLS_FILE_OPTION'/>
+		<param name='LINKER_SYMBOLS_OPTION'/>
+		<param name='NEED_ENTRYPOINT_LIBRARY'/>
+		<param name='OUTPUT_OPTION' default='-o'/>
+		<param name='OUTPUTPATH'/>
+		<param name='OWN_LIBRARY_OPTION'/>
+		<param name='PERL'/>
+		<param name='PERTURBSTARTTIME'/>
+		<param name='PERTURBMSECS' default='500'/>
+		<param name='POSTLINKER_COMPRESSION_DEFAULT'/>
+		<param name='POSTLINKER_FPU_DEFAULT'/>
+		<param name='PREPDEF'/>
+		<param name='PREINCLUDE'/>
+		<param name='PREINCLUDE_OPTION'/>
+		<param name='PREPROCESSOR_OPTION'/>
+		<param name='RANSLEEP'/>
+		<param name='RELEASEPATH'/>
+		<param name='RESOLVED_DEFFILE'/>
+		<param name='RUNTIME_LIBS_LIST'/>
+		<param name='RUNTIME_LIBS_PATH'/>
+		<param name='RUNTIME_SYMBOL_VISIBILITY_OPTION'/>
+		<param name='NO_UNALIGNED_ACCESS' default=''/>
+		<param name='RVCTBIN'/>
+		<param name='RVCTINC'/>
+		<param name='RVCTLIB'/>
+		<param name='RW_BASE'/>
+		<param name='RW_BASE_OPTION'/>
+		<param name='SBSV1MAKE'/>
+		<param name='NMAKE'/>
+		<param name='NMAKEFLAGS'/>
+		<param name='SHARED_OBJECT_OPTION'/>
+		<param name='SO_NAME_OPTION'/>
+		<param name='SPLIT_OPTION'/>
+		<param name='KERNEL_STATIC_RUNTIME_LIB'/>
+		<param name='USER_STATIC_RUNTIME_LIB'/>
+		<param name='USER_STATIC_RUNTIME_LIB_NESTED_EXCEPTIONS'/>
+		<param name='STATIC_LIBS_LIST'/>
+		<param name='STATIC_LIBS_PATH'/>
+		<param name='STATIC_LIBRARY_DIR'/>
+		<param name='STATIC_RUNTIME_DIR'/>
+		<param name='SUPPORTS_ABIV1_IMPLIBS'/>		
+		<param name='SYMBIAN_CCFLAGS'/>
+		<param name='SYMBIAN_LD_MESSAGE_OPTION'/>
+		<param name='SYMBIAN_LINK_FLAGS'/>
+		<param name='SYMVER_OPTION'/>
+		<param name='TARGET_ARCH_OPTION'/>
+		<param name='LINKER_ARCH_OPTION'/>
+		<param name='TESTCODE' default=''/>
+		<param name='TEST_OPTION' default=''/>
+		<param name='TRANSFORM_CIA'/>
+		<param name='USE_TRACE_COMPILER' default=''/>
+		<param name='TRANASM'/>
+		<param name='INSTRUCTION_SET'/>
+		<param name='MODULE'/>
+		<param name='USER_LIBS_PATH_OPTION'/>
+		<param name='VARIANTPLATFORM'/>
+		<param name='PLATFORM' default='$(VARIANTPLATFORM)'/>
+		<param name='VARIANTTYPE'/>
+		<param name='VERSION' default='10.0'/>
+		<param name='VERSIONHEX' default='000a0000'/>
+		<param name='VFE_OPTION'/>
+		<param name='EXPLICITVERSION' default=''/>
+	</interface>
+	<interface name="Symbian.exe" extends="Symbian.e32abiv2" flm="e32abiv2exe.flm">
+		<param name='TARGETTYPE' default="exe"/>
+		<param name='UID1' default="1000007a"/>
+	</interface>
+	<interface name="Symbian.stdexe" extends="Symbian.e32abiv2" flm="e32abiv2stdexe.flm">
+		<param name='TARGETTYPE' default="stdexe"/>
+		<param name='UID1' default="1000007a"/>
+		<param name='UID2' default="20004c45"/>
+		<param name='WCHARENTRYPOINT' default=""/>
+	</interface>
+	<interface name="Symbian.dll" extends="Symbian.e32abiv2" flm="e32abiv2dll.flm">
+		<param name='TARGETTYPE' default="dll"/>
+		<param name='UID1' default="10000079"/>
+	</interface>
+	<interface name="Symbian.pdll" extends="Symbian.e32abiv2" flm="e32abiv2pdll.flm">
+		<param name='TARGETTYPE' default="pdll"/>
+		<param name='UID1' default="10000079"/>
+	</interface>
+	<interface name="Symbian.stddll" extends="Symbian.e32abiv2" flm="e32abiv2stddll.flm">
+		<param name='TARGETTYPE' default="stddll"/>
+		<param name='UID1' default="10000079"/>
+		<param name='UID2' default="20004c45"/>
+	</interface>
+	<interface name="Symbian.lib" extends="Symbian.e32abiv2" flm="e32abiv2lib.flm">
+		<param name='AR'/>
+		<param name='ARCHIVER_CREATE_OPTION'/>
+		<param name='TARGETTYPE' default="lib"/>
+	</interface>
+	<interface name="Symbian.stdlib" extends="Symbian.lib" flm="e32abiv2stdlib.flm">
+		<param name='TARGETTYPE' default="stdlib"/>
+	</interface>
+	<interface name="Symbian.extension" extends="base.extension" flm="template_ext.flm">
+		<param name='RVCTBIN'/>
+		<param name='RVCTLIB'/>
+		<param name='RVCTINC'/>
+	</interface>
+	<interface name="Symbian.ani" extends="Symbian.dll" flm="e32abiv2ani.flm">
+	</interface>
+	<interface name="Symbian.plugin" extends="Symbian.dll" flm="e32abiv2plugin.flm">
+	</interface>
+	<interface name="Symbian.plugin3" extends="Symbian.dll" flm="e32abiv2plugin.flm">
+	</interface>
+	<interface name="Symbian.textnotifier2" extends="Symbian.dll" flm="e32abiv2textnotifier2.flm">
+	</interface>
+	<interface name="Symbian.implib" extends="Symbian.dll" flm="e32abiv2implib.flm">
+	</interface>
+	<interface name="Symbian.var" extends="Symbian.dll" flm="e32abiv2var.flm">
+	</interface>
+	<interface name="Symbian.var2" extends="Symbian.dll" flm="e32abiv2var2.flm">
+	</interface>
+	<interface name="Symbian.exexp" extends="Symbian.exe" flm="e32abiv2exexp.flm">
+	</interface>
+	<interface name="Symbian.kexe" extends="Symbian.exe" flm="e32abiv2kexe.flm">
+	</interface>
+	<interface name="Symbian.kdll" extends="Symbian.dll" flm="e32abiv2kdll.flm">
+	</interface>
+	<interface name="Symbian.kext" extends="Symbian.dll" flm="e32abiv2kext.flm">
+	</interface>
+	<interface name="Symbian.klib" extends="Symbian.lib" flm="e32abiv2klib.flm">
+	</interface>
+	<interface name="Symbian.ldd" extends="Symbian.dll" flm="e32abiv2ldd.flm">
+	</interface>
+	<interface name="Symbian.pdd" extends="Symbian.dll" flm="e32abiv2pdd.flm">
+	</interface>
+	<interface name="Symbian.pdl" extends="Symbian.dll" flm="e32abiv2pdl.flm">
+	</interface>
+	<interface name="Symbian.fsy" extends="Symbian.dll" flm="e32abiv2fsy.flm">
+	</interface>
+	<interface name="Symbian.none" extends="Symbian.mmp" flm="none.flm">
+	</interface>
+</build>
--- a/sbsv2/raptor/lib/flm/stringtable.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/stringtable.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,106 +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:
-# Header file exporting Function Like Makefile (FLM)
-# The file destinations  relative to EPOCROOT
-# 
-#
-
-## Parameters that are expected:
-# SOURCE
-# HEADERONLY
-# OUTPUTPATH
-# EPOCROOT
-# EXPORTPATH
-
-## GLOBAL TARGETS ###############################################
-.PHONY:: $(ALLTARGET)
-$(ALLTARGET):: $(RELEASEABLES)
-
-
-# StringTable FLM
-
-
-EXPORT::
-
-
-CLEANTARGETS:=
-CLEANEXPORTS:=
-RELEASEEXPORTS:=
-CREATABLEPATHS:=$(OUTPUTPATH) $(EXPORTPATH)
-
-# Work out the names of the various output files before
-# trying to use them in rules and dependencies. Cuts repetition
-# and avoids mistakes.
-EXPORTEDSTRINGTABLEHEADER:=$(EXPORTPATH)/$(TARGET).h
-STRINGTABLECPP:=$(OUTPUTPATH)/$(TARGET).cpp
-STRINGTABLEHEADER:=$(OUTPUTPATH)/$(TARGET).h
-STRINGTABLEPHONYTARGET:=$(OUTPUTPATH)_$(TARGET)
-TEMPSOURCE:=$(OUTPUTPATH)/$(TARGET).st
-
-# Macro to generate string table targets and rules
-# Always return true if the make engine doesn't support 
-# the .IGNORE:: target.
-define exportstringtableheader
-
-EXPORT:: $(EXPORTEDSTRINGTABLEHEADER)
-
-$(EXPORTEDSTRINGTABLEHEADER): $(STRINGTABLEHEADER) 
-	$(call startrule,exportstringtableheader,FORCESUCCESS) \
-	$(GNUCP) '$(STRINGTABLEHEADER)' '$$@'  \
-	$(call endrule,exportstringtableheader) 
-
-CLEANEXPORTS:=$(EXPORTEDSTRINGTABLEHEADER)
-RELEASEEXPORTS:=$(EXPORTEDSTRINGTABLEHEADER)
-endef
-
-define genstringtable
-$(STRINGTABLECPP) : $(STRINGTABLEHEADER)
-
-$(STRINGTABLEHEADER): $(SOURCE) 
-	$(call startrule,stringtable,FORCESUCCESS) \
-	$(GNUCP) --no-preserve=mode $(SOURCE) $(TEMPSOURCE)  && $(GNUCHMOD) a+w $(TEMPSOURCE) &&  \
-	$(STRINGTABLE) $(TEMPSOURCE)  \
-	$(call endrule,stringtable)
-
-CLEANTARGETS:=$(STRINGTABLEHEADER) $(STRINGTABLECPP)
-
-endef
-
-
-$(if $(EXPORTPATH),$(eval $(exportstringtableheader)),)
-$(if $(EXPORTPATH),,$(eval EXPORT:: $(STRINGTABLEHEADER)))
-$(eval $(genstringtable))
-
-
-## Clean up and log releasables (using eval to avoid target specific variables)
-$(eval $(call GenerateStandardCleanTarget,$(CLEANTARGETS),$(CREATABLEPATHS),))
-$(eval $(call GenerateStandardCleanTarget,$(CLEANEXPORTS),,CLEANEXPORT))
-# make the output directories while reading makefile - some build engines prefer this
-$(call makepath,$(CREATABLEPATHS))
-$(eval $(call whatmacro,$(RELEASEEXPORTS),WHATSTRINGTABLE))
-
-########################
-# SBSv1 example:
-########################
-# GENERATED_FILES= \
-#         $(EPOCROOT)epoc32\build\generated\http\WspParamConstants.cpp \
-#         $(EPOCROOT)epoc32\include\WspParamConstants.h
-# 
-# $(EPOCROOT)epoc32\build\generated\http\WspParamConstants.cpp : ..\strings\WspParamConstants.st
-#         perl -S ecopyfile.pl ..\strings\WspParamConstants.st $(EPOCROOT)epoc32\build\generated\http\WspParamConstants.st
-#         perl $(EPOCROOT)epoc32\tools\stringtable.pl $(EPOCROOT)epoc32\build\generated\http\WspParamConstants.st
-# 
-# $(EPOCROOT)epoc32\include\WspParamConstants.h : $(EPOCROOT)epoc32\build\generated\http\WspParamConstants.cpp
-#         perl -S ecopyfile.pl $(EPOCROOT)epoc32\build\generated\http\WspParamConstants.h $(EPOCROOT)epoc32\include\WspParamConstants.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:
+# Header file exporting Function Like Makefile (FLM)
+# The file destinations  relative to EPOCROOT
+# 
+#
+
+## Parameters that are expected:
+# SOURCE
+# HEADERONLY
+# OUTPUTPATH
+# EPOCROOT
+# EXPORTPATH
+
+## GLOBAL TARGETS ###############################################
+.PHONY:: $(ALLTARGET)
+$(ALLTARGET):: $(RELEASEABLES)
+
+
+# StringTable FLM
+
+
+EXPORT::
+
+CLEANTARGETS:=
+RELEASEEXPORTS:=
+CREATABLEPATHS:=$(OUTPUTPATH) $(EXPORTPATH)
+
+# Work out the names of the various output files before
+# trying to use them in rules and dependencies. Cuts repetition
+# and avoids mistakes.
+EXPORTEDSTRINGTABLEHEADER:=$(EXPORTPATH)/$(TARGET).h
+STRINGTABLECPP:=$(OUTPUTPATH)/$(TARGET).cpp
+STRINGTABLEHEADER:=$(OUTPUTPATH)/$(TARGET).h
+STRINGTABLEPHONYTARGET:=$(OUTPUTPATH)_$(TARGET)
+TEMPSOURCE:=$(OUTPUTPATH)/$(TARGET).st
+
+# Macro to generate string table targets and rules
+# Always return true if the make engine doesn't support 
+# the .IGNORE:: target.
+define exportstringtableheader
+
+EXPORT:: $(EXPORTEDSTRINGTABLEHEADER)
+
+$(EXPORTEDSTRINGTABLEHEADER): $(STRINGTABLEHEADER) 
+	$(call startrule,exportstringtableheader,FORCESUCCESS) \
+	$(GNUCP) '$(STRINGTABLEHEADER)' '$$@'  \
+	$(call endrule,exportstringtableheader) 
+
+RELEASEEXPORTS:=$(EXPORTEDSTRINGTABLEHEADER)
+endef
+
+define genstringtable
+$(STRINGTABLECPP) : $(STRINGTABLEHEADER)
+
+$(STRINGTABLEHEADER): $(SOURCE) 
+	$(call startrule,stringtable,FORCESUCCESS) \
+	$(GNUCP) --no-preserve=mode $(SOURCE) $(TEMPSOURCE)  && $(GNUCHMOD) a+w $(TEMPSOURCE) &&  \
+	$(STRINGTABLE) $(TEMPSOURCE)  \
+	$(call endrule,stringtable)
+
+CLEANTARGETS:=$(STRINGTABLEHEADER) $(STRINGTABLECPP)
+
+endef
+
+
+$(if $(EXPORTPATH),$(eval $(exportstringtableheader)),)
+$(if $(EXPORTPATH),,$(eval EXPORT:: $(STRINGTABLEHEADER)))
+$(eval $(genstringtable))
+
+
+## Clean up and log releasables
+$(call raptor_clean,$(CLEANTARGETS))
+# make the output directories while reading makefile - some build engines prefer this
+$(call makepath,$(CREATABLEPATHS))
+$(call raptor_release,$(RELEASEEXPORTS),STRINGTABLE)
+
--- a/sbsv2/raptor/lib/flm/taggedrules.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/taggedrules.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,138 +1,138 @@
-#
-# 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: 
-# Tools for use in FLMs - enabling the output from
-# rules to be logged with start and end tags.
-# This is a place where one might to permit various information to
-# be logged, such as timestamps and host names or process ids
-#
-
-ifndef _TAGGEDRULES_FLM_
-_TAGGEDRULES_FLM_:=1
-
-# only run recipes once by default
-RECIPETRIES?=1
-
-ifeq ($(USE_TALON),)
-
-##
-##  Example usage:
-##
-#   define func
-#	auto_ok:
-#		$(call startrule,auto) \
-#		true && \
-#		true && \
-#		true    \
-#		$(call endrule,auto)
-#	
-#	auto_fail:
-#		$(call startrule,auto) \
-#		find /usr >/dev/null 2>&1 && \
-#		false && \
-#		true    \
-#		$(call endrule,auto)
-#   endef
-#   $(eval $(func))
-
-# $(1) is the name of the FLM function
-# $(2) indicates whether the failure of this rule should be ignored (but still logged)
-#      FORCESUCCESS indicates "on"
-define startrule
-  @set -o pipefail; RV=0; ATTEMPT=1; \
-  { while (( $$$$ATTEMPT <= $(RECIPETRIES) )); do \
-    echo -e "<recipe name='$(1)' \
-    target='$$@' host='$$$$HOSTNAME' \
-    layer='$(COMPONENT_LAYER)' component='$(COMPONENT_NAME)' \
-    bldinf='$(COMPONENT_META)' mmp='$(PROJECT_META)' \
-    config='$(SBS_CONFIGURATION)' platform='$(PLATFORM)' \
-    phase='$(MAKEFILE_GROUP)' \
-    source='$(3)'>\n<![CDATA["; \
-    FLM_RECIPE_FLAGS='$(2)'; \
-    export TIMEFORMAT="]]><time start='$$$$($(DATE) +%s.%N)' elapsed='%6R' />"; \
-    { time { set -x;
-endef
-
-define endrule
-    ; }  } 2>&1  ; RV=$$$$?; set +x; \
-    if (( $$$$RV==0  )); then \
-       echo "<status exit='ok' attempt='$$$$ATTEMPT' />";  \
-       echo "</recipe>"; \
-       break; \
-    else  \
-       if (( $$$$ATTEMPT < $(RECIPETRIES) )); then \
-         echo "<status exit='retry' code='$$$$RV' attempt='$$$$ATTEMPT' />"; \
-         sleep 1; \
-       else \
-         if [ ! "$$$${FLM_RECIPE_FLAGS//FORCESUCCESS/}" == "$$$${FLM_RECIPE_FLAGS}" ]; then \
-             echo "<status exit='failed' code='$$$$RV' attempt='$$$$ATTEMPT' forcesuccess='FORCESUCCESS' />"; \
-             RV=0; \
-         else \
-             echo "<status exit='failed' code='$$$$RV' attempt='$$$$ATTEMPT' />"; \
-         fi; \
-       fi; \
-    fi; \
-    echo "</recipe>"; \
-    (( ATTEMPT=$$$$ATTEMPT + 1 )); \
-  done ; exit $$$${RV}; } $(if $(DESCRAMBLE),2>&1 | $(DESCRAMBLE) -k $$$$$$$$) 
-endef
-
-
-define startrawoutput
-  @ set -o pipefail; { 
-endef
-
-define endrawoutput
-  ; exit 0; } $(if $(DESCRAMBLE),2>&1 | $(DESCRAMBLE) -k $$$$$$$$) 
-endef
-
-
-else
-TALON_RECIPEATTRIBUTES:=\
- name='$$RECIPE'\
- target='$$TARGET'\
- host='$$HOSTNAME'\
- layer='$$COMPONENT_LAYER'\
- component='$$COMPONENT_NAME'\
- bldinf='$$COMPONENT_META' mmp='$$PROJECT_META'\
- config='$$SBS_CONFIGURATION' platform='$$PLATFORM'\
- phase='$$MAKEFILE_GROUP' source='$$SOURCE'
-
-export TALON_RECIPEATTRIBUTES
-export TALON_RETRIES
-export TALON_DESCRAMBLE
-
-define startrule
-	@|RECIPE=$1;TARGET=$$@;COMPONENT_LAYER=$(COMPONENT_LAYER);COMPONENT_NAME=$(COMPONENT_NAME);COMPONENT_META=$(COMPONENT_META);PROJECT_META=$(PROJECT_META);SBS_CONFIGURATION=$(SBS_CONFIGURATION);PLATFORM=$(PLATFORM);MAKEFILE_GROUP=$(MAKEFILE_GROUP);SOURCE=$3;TALON_FLAGS=$2;|
-endef
-
-define endrule
-endef
-
-
-define startrawoutput
-	@|TALON_FLAGS=forcesuccess rawoutput;|
-endef
-
-define endrawoutput
-endef
-
-
-
-endif
-
-
-
-
-endif
+#
+# 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: 
+# Tools for use in FLMs - enabling the output from
+# rules to be logged with start and end tags.
+# This is a place where one might to permit various information to
+# be logged, such as timestamps and host names or process ids
+#
+
+ifndef _TAGGEDRULES_FLM_
+_TAGGEDRULES_FLM_:=1
+
+# only run recipes once by default
+RECIPETRIES?=1
+
+ifeq ($(USE_TALON),)
+
+##
+##  Example usage:
+##
+#   define func
+#	auto_ok:
+#		$(call startrule,auto) \
+#		true && \
+#		true && \
+#		true    \
+#		$(call endrule,auto)
+#	
+#	auto_fail:
+#		$(call startrule,auto) \
+#		find /usr >/dev/null 2>&1 && \
+#		false && \
+#		true    \
+#		$(call endrule,auto)
+#   endef
+#   $(eval $(func))
+
+# $(1) is the name of the FLM function
+# $(2) indicates whether the failure of this rule should be ignored (but still logged)
+#      FORCESUCCESS indicates "on"
+define startrule
+  @set -o pipefail; RV=0; ATTEMPT=1; \
+  { while (( $$$$ATTEMPT <= $(RECIPETRIES) )); do \
+    echo -e "<recipe name='$(1)' \
+    target='$$@' host='$$$$HOSTNAME' \
+    layer='$(COMPONENT_LAYER)' component='$(COMPONENT_NAME)' \
+    bldinf='$(COMPONENT_META)' mmp='$(PROJECT_META)' \
+    config='$(SBS_CONFIGURATION)' platform='$(PLATFORM)' \
+    phase='$(MAKEFILE_GROUP)' \
+    source='$(3)'>\n<![CDATA["; \
+    FLM_RECIPE_FLAGS='$(2)'; \
+    export TIMEFORMAT="]]><time start='$$$$($(DATE) +%s.%N)' elapsed='%6R' />"; \
+    { time { set -x;
+endef
+
+define endrule
+    ; }  } 2>&1  ; RV=$$$$?; set +x; \
+    if (( $$$$RV==0  )); then \
+       echo "<status exit='ok' attempt='$$$$ATTEMPT' />";  \
+       echo "</recipe>"; \
+       break; \
+    else  \
+       if (( $$$$ATTEMPT < $(RECIPETRIES) )); then \
+         echo "<status exit='retry' code='$$$$RV' attempt='$$$$ATTEMPT' />"; \
+         sleep 1; \
+       else \
+         if [ ! "$$$${FLM_RECIPE_FLAGS//FORCESUCCESS/}" == "$$$${FLM_RECIPE_FLAGS}" ]; then \
+             echo "<status exit='failed' code='$$$$RV' attempt='$$$$ATTEMPT' forcesuccess='FORCESUCCESS' />"; \
+             RV=0; \
+         else \
+             echo "<status exit='failed' code='$$$$RV' attempt='$$$$ATTEMPT' />"; \
+         fi; \
+       fi; \
+    fi; \
+    echo "</recipe>"; \
+    (( ATTEMPT=$$$$ATTEMPT + 1 )); \
+  done ; exit $$$${RV}; } $(if $(DESCRAMBLE),2>&1 | $(DESCRAMBLE) -k $$$$$$$$) 
+endef
+
+
+define startrawoutput
+  @ set -o pipefail; { 
+endef
+
+define endrawoutput
+  ; exit 0; } $(if $(DESCRAMBLE),2>&1 | $(DESCRAMBLE) -k $$$$$$$$) 
+endef
+
+
+else
+TALON_RECIPEATTRIBUTES:=\
+ name='$$RECIPE'\
+ target='$$TARGET'\
+ host='$$HOSTNAME'\
+ layer='$$COMPONENT_LAYER'\
+ component='$$COMPONENT_NAME'\
+ bldinf='$$COMPONENT_META' mmp='$$PROJECT_META'\
+ config='$$SBS_CONFIGURATION' platform='$$PLATFORM'\
+ phase='$$MAKEFILE_GROUP' source='$$SOURCE'
+
+export TALON_RECIPEATTRIBUTES
+export TALON_RETRIES
+export TALON_DESCRAMBLE
+
+define startrule
+	@|RECIPE=$1;TARGET=$$@;COMPONENT_LAYER=$(COMPONENT_LAYER);COMPONENT_NAME=$(COMPONENT_NAME);COMPONENT_META=$(COMPONENT_META);PROJECT_META=$(PROJECT_META);SBS_CONFIGURATION=$(SBS_CONFIGURATION);PLATFORM=$(PLATFORM);MAKEFILE_GROUP=$(MAKEFILE_GROUP);SOURCE=$3;TALON_FLAGS=$2;|
+endef
+
+define endrule
+endef
+
+
+define startrawoutput
+	@|TALON_FLAGS=forcesuccess rawoutput;|
+endef
+
+define endrawoutput
+endef
+
+
+
+endif
+
+
+
+
+endif
--- a/sbsv2/raptor/lib/flm/template_ext.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/template_ext.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,230 +1,230 @@
-# 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:
-# Template Extension Makefile  (TEM) FLM
-# Knows how to run TEMs
-# 
-#
-
-################################# FLM Parameter description ##
-# Parameters:
-#   TEMPLATE_EXTENSION_MAKEFILE
-#   PRODUCT_INCLUDE
-#   EPOCROOT:=
-#   PLATFORM:=$(VARIANTPLATFORM)
-# The current configuration either UREL or UDEB:
-#   CFG:=$(VARIANTTYPE)
-# Relative path to EPOCROOT. (to where?):
-#   TO_ROOT:=
-# The path to the top-level bld.inf.
-# Note: if a bld.inf file #includes another bld.inf, this variable will
-# always contain the directory of that top-level file. If you require
-# the directory of the bld.inf which actually references the makefile,
-# use $(EXTENSION_ROOT) instead.
-#   TO_BLDINF:=
-# The project's working build directory under \epoc32\build\..
-#   EPOCBLD:=
-# The path to the directory containing the bld.inf in which the extension makefile was called:
-#   EXTENSION_ROOT:=
-# The path of the host-platform specific (i.e. the shell) makefile containing the above definitions:
-#   HOST_SHELL:=
-# The current platform in lower case to be used as part of path
-# names.
-#   PLATFORM_PATH:=
-# The current configuration in lower case to be used as part of
-# path names.
-#   CFG_PATH:=
-# A list of options passed from a bld.inf to this
-# Template Extension Makefile
-#  O._MEMBERS:=
-# Options should have the name specifed in the bld.inf 
-# but with a prefix of "O." e.g. O.PATH or O.FILENAME
-# (in which case O._MEMBERS:=PATH FILENAME)
-
-# create the working directory for the TEM
-$(shell $(GNUMKDIR) -p $(EPOCBLD))
-
-################################ Standard Variables ##
-# We may set the following 
-# for the sake of template
-# extension makefiles which
-# need to know them:
-
-## Path element separator.
-/:=/
-## PATH environment variable separator.
-;:=:
-
-####
-# Various file and directory manipulation tools.
-# We are using the standard GNU coretools.
-# On Windows these are supplied by CYGWIN
-RMDIR:=$(GNURMDIR)
-RM:=$(GNURM)
-ERASE:=$(GNURM)
-MKDIR:=$(GNUMKDIR)
-CP:=$(GNUCP)
-ARMV7BUILD:=
-
-######################## Target Specific Parameters ##
-# We need to declare the parameters for the TEM 
-# to be target specific to the unique targets
-# that we have created.
-
-UNIQ:=$(TEMPLATE_EXTENSION_MAKEFILE)$(PLATFORM)$(TO_ROOT)$(TO_BLDINF)$(EPOCBLD)$(EXTENSION_ROOT)$(TEMCOUNT)
-UNIQ:=$(word 1,$(shell echo $(UNIQ) | $(GNUMD5SUM)))
-
-# Work out the other FINAL target if we're building both udeb and urel
-ifneq ($($(UNIQ)),)
-
-ifeq ($(CFG),urel)
-OTHER_CFG:=udeb
-endif
-ifeq ($(CFG),udeb)
-OTHER_CFG:=urel
-endif
-ifeq ($(CFG),rel)
-OTHER_CFG:=deb
-endif
-ifeq ($(CFG),deb)
-OTHER_CFG:=rel
-endif
-
-OTHER_MAKMAKE:=$(UNIQ)_$(OTHER_CFG)_MAKMAKE
-OTHER_BLD:=$(UNIQ)_$(OTHER_CFG)_BLD
-OTHER_FREEZE:=$(UNIQ)_$(OTHER_CFG)_FREEZE
-OTHER_LIB:=$(UNIQ)_$(OTHER_CFG)_LIB
-OTHER_CLEANLIB:=$(UNIQ)_$(OTHER_CFG)_CLEANLIB
-OTHER_RESOURCE:=$(UNIQ)_$(OTHER_CFG)_RESOURCE
-OTHER_CLEAN:=$(UNIQ)_$(OTHER_CFG)_CLEAN
-OTHER_FINAL:=$(UNIQ)_$(OTHER_CFG)_FINAL
-endif # ifneq ($($(UNIQ)),)
-
-# Set $($(UNIQ)) so it can be detected if we're run again
-$(UNIQ):=1
-
-tem_$(notdir $(TEMPLATE_EXTENSION_MAKEFILE))_$(PLATFORM)_$(CFG):=$(tem_$(notdir $(TEMPLATE_EXTENSION_MAKEFILE))_$(PLATFORM)_$(CFG)) $(UNIQ)_$(CFG)
-
-TEPARAMETERS:= \
-	EPOCROOT PLATFORM CFG TO_ROOT TO_BLDINF \
-	EPOCBLD EXTENSION_ROOT HOST_SHELL       \
-	RMDIR RM ERASE MKDIR CP                 \
-	PLATFORM_PATH CFG_PATH                  \
-	TEMPLATE_EXTENSION_MAKEFILE             \
-	TARGET SOURCE DEPENDENCIES TOOL PRODUCT_INCLUDE \
-	RVCTBIN RVCTINC RVCTLIB
-
-
-# The standard Template Extension Makefile Targets
-# These will be implemented in terms of double colon
-# rules - such that make FREEZE will cause all FREEZE 
-# targets to be evaluated.
-# For each call of this FLM we also need
-# to create unique versions of each of these targets
-# so that there is something to attach
-# the current FLM parameters to using target-specific 
-# variable declarations.
-
-TETARGETS:= \
-	MAKMAKE     \
-	BLD         \
-	FREEZE      \
-	LIB         \
-	CLEANLIB    \
-	RESOURCE    \
-	CLEAN       \
-	RELEASABLES \
-	FINAL
-
-# If we split the makefiles then only use a subset of
-# the targets for each group makefile.
-#
-ifeq ($(MAKEFILE_GROUP),BITMAP)
-TETARGETS:=MAKMAKE
-endif
-#
-ifeq ($(MAKEFILE_GROUP),RESOURCE)
-TETARGETS:=RESOURCE
-endif
-#
-ifeq ($(MAKEFILE_GROUP),ALL)
-TETARGETS:=BLD FREEZE LIB CLEANLIB CLEAN RELEASABLES FINAL
-endif
-
-# Hook into global targets
-#
-MAKMAKE_HOOK:=BITMAP
-BLD_HOOK:=TARGET
-FREEZE_HOOK:=FREEZE
-LIB_HOOK:=LIBRARY
-CLEAN_HOOK:=CLEAN
-CLEANLIB_HOOK:=CLEAN
-RESOURCE_HOOK:=RESOURCE
-FINAL_HOOK:=FINAL
-RELEASABLES_HOOK:=RELEASABLES
-
-# make sure TEMS happen at the right stages
-# OTHER_$(STAGE) only set if running udeb+urel
-MAKMAKE_DEPS:=EXPORT $(OTHER_MAKMAKE)
-RESOURCE_DEPS:=BITMAP $(OTHER_RESOURCE)
-LIB_DEPS:=RESOURCE $(OTHER_LIB)
-BLD_DEPS:=LIBRARY $(OTHER_BLD)
-FINAL_DEPS:=TARGET $(OTHER_FINAL)
-FREEZE_DEPS:=$(OTHER_FREEZE)
-CLEANLIB_DEPS:=$(OTHER_CLEANLIB)
-CLEAN_DEPS:=$(OTHER_CLEAN)
-
-export /
-export ;
-export SHELL
-
-#################################### Global Targets ##
-## All the global targets for the TEM
-# TEMs are called as sub-makes.
-
-define getMember
-$(subst $$,$$$$,$(O.$(1)))
-endef
-
-define callTEM
-.PHONY:: $(UNIQ)_$(CFG)_$(1) 
-$($(1)_HOOK):: $(UNIQ)_$(CFG)_$(1)
-
-$(EPOCROOT)/epoc32/build/TEM_$(1):: $(UNIQ)_$(CFG)_$(1)
-
-$(UNIQ)_$(CFG)_$(1) : $($(1)_DEPS)
-	$(call startrule,tem,FORCESUCCESS,$(notdir $(TEMPLATE_EXTENSION_MAKEFILE))_$(1)) \
-	$(foreach V,$(TEPARAMETERS),$(V)='$($(V))') TEMTARGET='$(1)' $(foreach V,$(O._MEMBERS),$(V)='$(call getMember,$(V))')  $(TEMMAKE) -C $(EPOCBLD) -f $(TEMPLATE_EXTENSION_MAKEFILE) $(if $(SAVESPACE),$(subst BLD,SAVESPACE,$(1)),$(1)) \
-	$(call endrule,tem)
-ifneq ($(call isoneof,$(1),RELEASABLES FINAL),)
-	$(call startrawoutput) \
-	echo "$(call whatLogOpen)" ; \
-	$(foreach V,$(TEPARAMETERS),$(V)='$($(V))') TEMTARGET='$(1)' \
-	$(foreach V,$(O._MEMBERS),$(V)='$(call getMember,$(V))')  \
-	$(TEMMAKE) -s --no-print-directory -C $(EPOCBLD) -f $(TEMPLATE_EXTENSION_MAKEFILE) RELEASABLES | \
-	(read -r LINE; while [ $$$$? -eq 0 ]; do \
-	if [[ ! $$$$LINE =~ "Nothing to be done for"  ]] ; then echo "$(call whatLogItem,TEM,$$$$LINE)"; fi; \
-	read -r LINE; done; ); \
-	echo "$(call whatLogClose)" \
-	$(call endrawoutput) 
-
-WHATTEM:: $(UNIQ)_$(CFG)_RELEASABLES
-
-endif
-
-
-tem_debug::
-	@echo "TEM_DEBUG: O._MEMBERS=$(O._MEMBERS)"
-endef
-
-$(foreach TETRG,$(TETARGETS),$(eval $(call callTEM,$(TETRG))))
+# 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:
+# Template Extension Makefile  (TEM) FLM
+# Knows how to run TEMs
+# 
+#
+
+################################# FLM Parameter description ##
+# Parameters:
+#   TEMPLATE_EXTENSION_MAKEFILE
+#   PRODUCT_INCLUDE
+#   EPOCROOT:=
+#   PLATFORM:=$(VARIANTPLATFORM)
+# The current configuration either UREL or UDEB:
+#   CFG:=$(VARIANTTYPE)
+# Relative path to EPOCROOT. (to where?):
+#   TO_ROOT:=
+# The path to the top-level bld.inf.
+# Note: if a bld.inf file #includes another bld.inf, this variable will
+# always contain the directory of that top-level file. If you require
+# the directory of the bld.inf which actually references the makefile,
+# use $(EXTENSION_ROOT) instead.
+#   TO_BLDINF:=
+# The project's working build directory under \epoc32\build\..
+#   EPOCBLD:=
+# The path to the directory containing the bld.inf in which the extension makefile was called:
+#   EXTENSION_ROOT:=
+# The path of the host-platform specific (i.e. the shell) makefile containing the above definitions:
+#   HOST_SHELL:=
+# The current platform in lower case to be used as part of path
+# names.
+#   PLATFORM_PATH:=
+# The current configuration in lower case to be used as part of
+# path names.
+#   CFG_PATH:=
+# A list of options passed from a bld.inf to this
+# Template Extension Makefile
+#  O._MEMBERS:=
+# Options should have the name specifed in the bld.inf 
+# but with a prefix of "O." e.g. O.PATH or O.FILENAME
+# (in which case O._MEMBERS:=PATH FILENAME)
+
+# create the working directory for the TEM
+$(shell $(GNUMKDIR) -p $(EPOCBLD))
+
+################################ Standard Variables ##
+# We may set the following 
+# for the sake of template
+# extension makefiles which
+# need to know them:
+
+## Path element separator.
+/:=/
+## PATH environment variable separator.
+;:=:
+
+####
+# Various file and directory manipulation tools.
+# We are using the standard GNU coretools.
+# On Windows these are supplied by CYGWIN
+RMDIR:=$(GNURMDIR)
+RM:=$(GNURM)
+ERASE:=$(GNURM)
+MKDIR:=$(GNUMKDIR)
+CP:=$(GNUCP)
+ARMV7BUILD:=
+
+######################## Target Specific Parameters ##
+# We need to declare the parameters for the TEM 
+# to be target specific to the unique targets
+# that we have created.
+
+UNIQ:=$(TEMPLATE_EXTENSION_MAKEFILE)$(VARIANTPLATFORM)$(TO_ROOT)$(TO_BLDINF)$(EPOCBLD)$(EXTENSION_ROOT)$(TEMCOUNT)
+UNIQ:=$(word 1,$(shell echo $(UNIQ) | $(GNUMD5SUM)))
+
+# Work out the other FINAL target if we're building both udeb and urel
+
+ifeq ($(CFG),urel)
+OTHER_CFG:=udeb
+endif
+ifeq ($(CFG),udeb)
+OTHER_CFG:=urel
+endif
+ifeq ($(CFG),rel)
+OTHER_CFG:=deb
+endif
+ifeq ($(CFG),deb)
+OTHER_CFG:=rel
+endif
+
+ifneq ($($(UNIQ)_$(OTHER_CFG)),)
+OTHER_MAKMAKE:=$(UNIQ)_$(OTHER_CFG)_MAKMAKE
+OTHER_BLD:=$(UNIQ)_$(OTHER_CFG)_BLD
+OTHER_FREEZE:=$(UNIQ)_$(OTHER_CFG)_FREEZE
+OTHER_LIB:=$(UNIQ)_$(OTHER_CFG)_LIB
+OTHER_CLEANLIB:=$(UNIQ)_$(OTHER_CFG)_CLEANLIB
+OTHER_RESOURCE:=$(UNIQ)_$(OTHER_CFG)_RESOURCE
+OTHER_CLEAN:=$(UNIQ)_$(OTHER_CFG)_CLEAN
+OTHER_FINAL:=$(UNIQ)_$(OTHER_CFG)_FINAL
+endif # ifneq ($($(UNIQ)),)
+
+# Set $($(UNIQ)) so it can be detected if we're run again
+$(UNIQ)_$(CFG):=1
+
+tem_$(notdir $(TEMPLATE_EXTENSION_MAKEFILE))_$(PLATFORM)_$(CFG):=$(tem_$(notdir $(TEMPLATE_EXTENSION_MAKEFILE))_$(PLATFORM)_$(CFG)) $(UNIQ)_$(CFG)
+
+TEPARAMETERS:= \
+	EPOCROOT PLATFORM CFG TO_ROOT TO_BLDINF \
+	EPOCBLD EXTENSION_ROOT HOST_SHELL       \
+	RMDIR RM ERASE MKDIR CP                 \
+	PLATFORM_PATH CFG_PATH                  \
+	TEMPLATE_EXTENSION_MAKEFILE             \
+	PRODUCT_INCLUDE \
+	RVCTBIN RVCTINC RVCTLIB
+
+
+# The standard Template Extension Makefile Targets
+# These will be implemented in terms of double colon
+# rules - such that make FREEZE will cause all FREEZE 
+# targets to be evaluated.
+# For each call of this FLM we also need
+# to create unique versions of each of these targets
+# so that there is something to attach
+# the current FLM parameters to using target-specific 
+# variable declarations.
+
+TETARGETS:= \
+	MAKMAKE     \
+	BLD         \
+	FREEZE      \
+	LIB         \
+	CLEANLIB    \
+	RESOURCE    \
+	CLEAN       \
+	RELEASABLES \
+	FINAL
+
+# If we split the makefiles then only use a subset of
+# the targets for each group makefile.
+#
+ifeq ($(MAKEFILE_GROUP),BITMAP)
+TETARGETS:=MAKMAKE
+endif
+#
+ifeq ($(MAKEFILE_GROUP),RESOURCE)
+TETARGETS:=RESOURCE
+endif
+#
+ifeq ($(MAKEFILE_GROUP),ALL)
+TETARGETS:=BLD FREEZE LIB CLEANLIB CLEAN RELEASABLES FINAL
+endif
+
+# Hook into global targets
+#
+MAKMAKE_HOOK:=BITMAP
+BLD_HOOK:=TARGET
+FREEZE_HOOK:=FREEZE
+LIB_HOOK:=LIBRARY
+CLEAN_HOOK:=CLEAN
+CLEANLIB_HOOK:=CLEAN
+RESOURCE_HOOK:=RESOURCE
+FINAL_HOOK:=FINAL
+RELEASABLES_HOOK:=RELEASABLES
+
+# make sure TEMS happen at the right stages
+# OTHER_$(STAGE) only set if running udeb+urel
+MAKMAKE_DEPS:=EXPORT $(OTHER_MAKMAKE)
+RESOURCE_DEPS:=BITMAP $(OTHER_RESOURCE)
+LIB_DEPS:=RESOURCE $(OTHER_LIB)
+BLD_DEPS:=LIBRARY $(OTHER_BLD)
+FINAL_DEPS:=TARGET $(OTHER_FINAL)
+FREEZE_DEPS:=$(OTHER_FREEZE)
+CLEANLIB_DEPS:=$(OTHER_CLEANLIB)
+CLEAN_DEPS:=$(OTHER_CLEAN)
+
+export /
+export ;
+export SHELL
+
+#################################### Global Targets ##
+## All the global targets for the TEM
+# TEMs are called as sub-makes.
+
+define getMember
+$(subst $$,$$$$,$(O.$(1)))
+endef
+
+define callTEM
+.PHONY:: $(UNIQ)_$(CFG)_$(1) 
+$($(1)_HOOK):: $(UNIQ)_$(CFG)_$(1)
+
+$(EPOCROOT)/epoc32/build/TEM_$(1):: $(UNIQ)_$(CFG)_$(1)
+
+$(UNIQ)_$(CFG)_$(1) : $($(1)_DEPS)
+	$(call startrule,tem,FORCESUCCESS,$(notdir $(TEMPLATE_EXTENSION_MAKEFILE))_$(1)) \
+	$(foreach V,$(TEPARAMETERS),$(V)='$($(V))') TEMTARGET='$(1)' $(foreach V,$(O._MEMBERS),$(V)='$(call getMember,$(V))')  $(TEMMAKE) -C $(EPOCBLD) -f $(TEMPLATE_EXTENSION_MAKEFILE) $(if $(SAVESPACE),$(subst BLD,SAVESPACE,$(1)),$(1)) \
+	$(call endrule,tem)
+ifneq ($(call isoneof,$(1),RELEASABLES FINAL),)
+	$(call startrawoutput) \
+	echo "$(call whatLogOpen)" ; \
+	$(foreach V,$(TEPARAMETERS),$(V)='$($(V))') TEMTARGET='$(1)' \
+	$(foreach V,$(O._MEMBERS),$(V)='$(call getMember,$(V))')  \
+	$(TEMMAKE) -s --no-print-directory -C $(EPOCBLD) -f $(TEMPLATE_EXTENSION_MAKEFILE) RELEASABLES | \
+	(read -r LINE; while [ $$$$? -eq 0 ]; do \
+	if [[ ! $$$$LINE =~ "Nothing to be done for"  ]] ; then echo "$(call whatLogItem,TEM,$$$$LINE)"; fi; \
+	read -r LINE; done; ); \
+	echo "$(call whatLogClose)" \
+	$(call endrawoutput) 
+
+WHATTEM:: $(UNIQ)_$(CFG)_RELEASABLES
+
+endif
+
+
+tem_debug::
+	@echo "TEM_DEBUG: O._MEMBERS=$(O._MEMBERS)"
+endef
+
+$(foreach TETRG,$(TETARGETS),$(eval $(call callTEM,$(TETRG))))
--- a/sbsv2/raptor/lib/flm/test/Makefile	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/Makefile	Wed Jun 23 16:56:47 2010 +0800
@@ -1,66 +1,66 @@
-##
-# Create and check test environment.
-# build all tests.
-
-## Purpose: Run test makefiles in parallel to ensure that they all work
-## Postconditions: All postconditions for all the makefiles are satisfied
-
-# Parameters which may be overridden by the environment:
-RAPTOR_HOME?=/localhome/tmurphy/pf/EPOC/development/tools/personal/tmurphy/tools/raptor
-# Need elf2e32 etc.
-RAPTOOLS?=/localhome/tmurphy/raptools/linux86
-EPOCROOT?=/tmp/tim-epocroot
-# End of Environment-overridable parameters.
-
-#Where are flms located?
-FLMHOME:=$(RAPTOR_HOME)/lib/flm
-FLMTESTHOME:=$(FLMHOME)/test
-SOURCEPATH:=$(FLMHOME)/test
-
-
-.PHONY:: all
-
-#### Call all the test makefiles ##############
-ALLTARGET:=all
-
-OUTPUTPATH=$(EPOCROOT)/epoc32/build
-RELEASEPATH:=$(EPOCROOT)/epoc32/release
-FULLVARIANTPATH:=ARMV5/UREL
-
-include $(FLMHOME)/test/exebasictests.mk
-
-include $(FLMHOME)/test/ciatests.mk
-
-include $(FLMHOME)/test/exeperftests.mk
-
-include $(FLMHOME)/test/dllbasictests.mk
-
-###############################################
-
-#EPOCROOT:=
-SYSTEMSOURCEPATH:=/c/p4_Perforce011666_LON-TIMOTHYM01/EPOC/development/tools/personal/tmurphy/EPOC/master
-OSNAME:=cedar
-#include $(FLMHOME)/system.flm
-
-flmcheck:: flmtoolscheck
-	@ERRCOUNT=0; for i in $(FLMHOME)/*.flm; do \
-		$(FLMHOME)/tools/flmcheck.py  $$i; ERRCOUNT=$$[ $$ERRCOUNT + $$?];  done;  \
-		echo "flmcheck issued warnings for $$ERRCOUNT  FLMS.";
-		@true # For the time being this is not a sufficient condition to stop the tests
-
-# Run through the flmtools tests to make sure thye work
-flmtoolscheck::
-	make -f ../flmtools.mk STANDALONE_TEST:=1 FLMHOME:=$(FLMHOME) test
-
-envcheck::
-	@echo "<envcheck>"
-	@echo -n "<elf2e32>"; ELF2E32=`which elf2e32`; if [ "$$ELF2E32" == "" ]; then echo -n "elf2e32 not available in the path."; else echo -n "$$ELF2E32"; fi; echo "<elf2e32>"
-	@echo -n "<make>"; make -v | egrep '^.*GNU Make 3.81.*$$' ; if [ $$? -ne 0 ]; then echo -n "Version of make in the path appears not to be 3.81."; fi; echo "<make>"
-	@echo -n "<tranasm>"; $$TRANASM | egrep 'tranasm' ; if [ $$? -ne 0 ]; then echo -n "tranasm not found"; fi; echo "<tranasm>"
-	@echo -n "<epocroot>"; if [ ! -d "$$EPOCROOT" ]; then echo -n "EPOCROOT='$$EPOCROOT' directory not found."; else echo -n "$$EPOCROOT"; fi; echo "</epocroot>"
-	@echo -n "<raptorhome>"; if [ ! -d "$$RAPTOR_HOME" ]; then echo -n "RAPTOR_HOME='$$RAPTOR_HOME' directory not found."; else echo -n "$$RAPTOR_HOME"; fi; echo "</raptorhome>"
-	@echo "</envcheck>"
-
-	
-	
-# END TEST - Check FLMS
+##
+# Create and check test environment.
+# build all tests.
+
+## Purpose: Run test makefiles in parallel to ensure that they all work
+## Postconditions: All postconditions for all the makefiles are satisfied
+
+# Parameters which may be overridden by the environment:
+RAPTOR_HOME?=/localhome/tmurphy/pf/EPOC/development/tools/personal/tmurphy/tools/raptor
+# Need elf2e32 etc.
+RAPTOOLS?=/localhome/tmurphy/raptools/linux86
+EPOCROOT?=/tmp/tim-epocroot
+# End of Environment-overridable parameters.
+
+#Where are flms located?
+FLMHOME:=$(RAPTOR_HOME)/lib/flm
+FLMTESTHOME:=$(FLMHOME)/test
+SOURCEPATH:=$(FLMHOME)/test
+
+
+.PHONY:: all
+
+#### Call all the test makefiles ##############
+ALLTARGET:=all
+
+OUTPUTPATH=$(EPOCROOT)/epoc32/build
+RELEASEPATH:=$(EPOCROOT)/epoc32/release
+FULLVARIANTPATH:=ARMV5/UREL
+
+include $(FLMHOME)/test/exebasictests.mk
+
+include $(FLMHOME)/test/ciatests.mk
+
+include $(FLMHOME)/test/exeperftests.mk
+
+include $(FLMHOME)/test/dllbasictests.mk
+
+###############################################
+
+#EPOCROOT:=
+SYSTEMSOURCEPATH:=/c/p4_Perforce011666_LON-TIMOTHYM01/EPOC/development/tools/personal/tmurphy/EPOC/master
+OSNAME:=cedar
+#include $(FLMHOME)/system.flm
+
+flmcheck:: flmtoolscheck
+	@ERRCOUNT=0; for i in $(FLMHOME)/*.flm; do \
+		$(FLMHOME)/tools/flmcheck.py  $$i; ERRCOUNT=$$[ $$ERRCOUNT + $$?];  done;  \
+		echo "flmcheck issued warnings for $$ERRCOUNT  FLMS.";
+		@true # For the time being this is not a sufficient condition to stop the tests
+
+# Run through the flmtools tests to make sure thye work
+flmtoolscheck::
+	make -f ../flmtools.mk STANDALONE_TEST:=1 FLMHOME:=$(FLMHOME) test
+
+envcheck::
+	@echo "<envcheck>"
+	@echo -n "<elf2e32>"; ELF2E32=`which elf2e32`; if [ "$$ELF2E32" == "" ]; then echo -n "elf2e32 not available in the path."; else echo -n "$$ELF2E32"; fi; echo "<elf2e32>"
+	@echo -n "<make>"; make -v | egrep '^.*GNU Make 3.81.*$$' ; if [ $$? -ne 0 ]; then echo -n "Version of make in the path appears not to be 3.81."; fi; echo "<make>"
+	@echo -n "<tranasm>"; $$TRANASM | egrep 'tranasm' ; if [ $$? -ne 0 ]; then echo -n "tranasm not found"; fi; echo "<tranasm>"
+	@echo -n "<epocroot>"; if [ ! -d "$$EPOCROOT" ]; then echo -n "EPOCROOT='$$EPOCROOT' directory not found."; else echo -n "$$EPOCROOT"; fi; echo "</epocroot>"
+	@echo -n "<raptorhome>"; if [ ! -d "$$RAPTOR_HOME" ]; then echo -n "RAPTOR_HOME='$$RAPTOR_HOME' directory not found."; else echo -n "$$RAPTOR_HOME"; fi; echo "</raptorhome>"
+	@echo "</envcheck>"
+
+	
+	
+# END TEST - Check FLMS
--- a/sbsv2/raptor/lib/flm/test/ciaabiv2_1/ciaabiv2_1.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/ciaabiv2_1/ciaabiv2_1.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,42 +1,42 @@
-#
-# 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: 
-#
-##
-## Test 1 - build an ARM E32 EXE on Linux
-## parameters relevant to the test.
-
-## Purpose: To demonstrate use of 1 call to a basic flm with one input file
-## Postconditions: test1.cia is written to the output directory $OUTPUTPATH/test1/test1.cia:
-
-# Pull tools
-include $(FLMHOME)/flmtools.mk
-
-
-$(call vsave,OUTPUTPATH SOURCEPATH CDEFS SYSTEMINCLUDE)
-# Pull in defaults for building test ciacutables
-include $(FLMTESTHOME)/dllabiv2_defaults.mk
-
-TARGET:=ciaabiv2_1
-CDEFS:=$(CDEFS) __TESTNAME__=\"ciaabiv2_1\"
-OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)
-SOURCEPATH:=$(SOURCEPATH)/ciaabiv2_1
-SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(FLMTESTHOME)/include
-SOURCEFILES:=$(SOURCEPATH)/uc_exe.cia  $(SOURCEPATH)/uc_exe.cpp
-UID3:=0x000001
-
-
-include $(FLMHOME)/$(FLM)
-
-$(call vrestore)
+#
+# 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: 
+#
+##
+## Test 1 - build an ARM E32 EXE on Linux
+## parameters relevant to the test.
+
+## Purpose: To demonstrate use of 1 call to a basic flm with one input file
+## Postconditions: test1.cia is written to the output directory $OUTPUTPATH/test1/test1.cia:
+
+# Pull tools
+include $(FLMHOME)/flmtools.mk
+
+
+$(call vsave,OUTPUTPATH SOURCEPATH CDEFS SYSTEMINCLUDE)
+# Pull in defaults for building test ciacutables
+include $(FLMTESTHOME)/dllabiv2_defaults.mk
+
+TARGET:=ciaabiv2_1
+CDEFS:=$(CDEFS) __TESTNAME__=\"ciaabiv2_1\"
+OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)
+SOURCEPATH:=$(SOURCEPATH)/ciaabiv2_1
+SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(FLMTESTHOME)/include
+SOURCEFILES:=$(SOURCEPATH)/uc_exe.cia  $(SOURCEPATH)/uc_exe.cpp
+UID3:=0x000001
+
+
+include $(FLMHOME)/$(FLM)
+
+$(call vrestore)
--- a/sbsv2/raptor/lib/flm/test/ciaabiv2_1/uc_exe.cia	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/ciaabiv2_1/uc_exe.cia	Wed Jun 23 16:56:47 2010 +0800
@@ -1,128 +1,128 @@
-/*
-* 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: 
-* e32\euser\epoc\arm\uc_exe.cia
-*
-*/
-
-
-#include <e32cia.h>
-#include <u32std.h>
-// Include this to get imports from User (i.e. User::Invariant and User::HandleException). 
-// This sets VISIBILITY to DEFAULT for BPABI builds.
-#include <e32std.h>
-
-extern "C" {
-
-void _xxxx_call_user_invariant();
-void _xxxx_call_user_handle_exception(void *);
-
-extern void RunThread(TBool aNotFirst, SThreadCreateInfo& aInfo);
-
-// NOTE: This MUST be the first function in this module
-__NAKED__ TInt _E32Startup()
-	{
-	// Process entry point
-	// R4 = entry reason
-	// SP points to information block
-	EKA2_ENTRY_POINT_VERSION_IDENTIFIER;	// DUMMY INSTRUCTION TO INDICATE EKA2 ENTRY POINT
-	asm("cmp r4, #%a0" : : "i" ((TInt)KModuleEntryReasonThreadInit) );
-	asm("b 1f ");				// branch over space for unique ID
-
-	asm(".word 0 ");			// loader will replace with code seg unique ID
-								// for RAM-loaded code segment
-								// MUST BE AT OFFSET 12 FROM ENTRY POINT
-
-	asm("1: ");
-	asm("movls r0, r4 ");		// r0 = aNotFirst
-	asm("movls r1, sp ");		// r1 -> parameter block
-	asm("bls RunThread ");		// process or thread init
-	asm("cmp r4, #%a0" : : "i" ((TInt)KModuleEntryReasonException) );
-//  	asm("bne " CSM_ZN4User9InvariantEv );	// invalid entry reason
-  	asm("bne _xxxx_call_user_invariant " );	// invalid entry reason
-
-	// exception entry
-	// NOTE: THUMB only works on ARMv5 and above
-	asm("mov r0, sp ");			// r0->parameter block
-	asm("ldr r4, [sp, #16]");	// r4 = saved CPSR
-	asm("tst r4, #0x20 ");		// test for THUMB
-	asm("ldrne r1, [sp, #80] ");	// r1 = saved return addr
-	asm("orrne r1, r1, #1 ");
-	asm("strne r1, [sp, #80] ");	// if THUMB, set bit 0 of return addr
-
-	asm("mov r11, sp ");		// save stack pointer
-
-	// The frame starts 84 bytes (up) from r11 i.e. CFA is r11 + 84
-	__EH_FRAME_ADDRESS(r11, 84)
-	// we can only restore callee-save values, but that's what we want if we 'leave'
-	// saved link is -8 bytes from CFA (= r11 + 0x24 + 0x20 + 0x8)
-	__EH_FRAME_SAVE1(lr, -8)
-
-	// the other callee saves start at -48 from CFA (= r11 + 0x24)
-#if 0
-	// would like to say this 
-	__EH_FRAME_SAVE1(r4-r11, -48)
-	// but the macro expansion gives rise to odd code so we do what follows
-#endif
-#ifdef __ARMCC__
-	FRAME SAVE {r4-r11}, -48
-#endif
-
-	asm("bic sp, sp, #4 ");		// align stack to 8 byte boundary
-//  	asm("bl " CSM_ZN4User15HandleExceptionEPv );
-  	asm("bl _xxxx_call_user_handle_exception ");
-	asm("add sp, r11, #16 ");	// skip exc type, exc code, FAR, FSR
-	asm("ldr r4, [sp], #4 ");	// r4 = saved CPSR
-	asm("bic r4, r4, #0x20 ");	// clear THUMB bit
-	asm("msr cpsr, r4 ");		// restore flags
-	asm("ldmia sp, {r0-r15} ");	// restore r0-r15
-
-#ifdef __ARMCC__
-#ifdef __SUPPORT_CPP_EXCEPTIONS__
-
-
-  /* It is possible no functions included in the image require
-   * a handler table. Therefore make only a weak reference to
-   * the handler table base symbol, which may be absent.
-   */
-  extern |.ARM.exidx$$Base|;
-  extern |.ARM.exidx$$Limit|;
-  extern |.ARM.extab$$Base| [WEAK];
-  extern |Image$$ER_RO$$Base|;
-  extern |Image$$ER_RO$$Limit|;
-  export |Symbian$$CPP$$Exception$$Descriptor|;
-
-|Symbian$$CPP$$Exception$$Descriptor|
-#ifdef __LEAVE_EQUALS_THROW__
-|Symbian$$eit_base|  		dcd |.ARM.exidx$$Base|;   /* index table base */
-|Symbian$$eit_limit|  		dcd |.ARM.exidx$$Limit| ;  /* index table limit */
-#endif
-#if __ARMCC_VERSION > 220000
-|Symbian$$code_seg_base| 	dcd |Image$$ER_RO$$Base| + 1 ; /* RO segment base + mark as ehabi v2 */
-|Symbian$$code_seg_limit| 	dcd |Image$$ER_RO$$Limit| ;/* RO segment limit */
-|Symbian$$reserved|		dcd 0 ; /* reserved for future use */
-#else
-|Symbian$$code_seg_base| 	dcd |Image$$ER_RO$$Base| ; /* RO segment base */
-|Symbian$$code_seg_limit| 	dcd |Image$$ER_RO$$Limit| ;/* RO segment limit */
-#endif
-
-#endif
-#endif
-
-	}
-void _xxxx_call_user_invariant() { User::Invariant(); }
-void _xxxx_call_user_handle_exception(void * arg) { User::HandleException(arg); }
-
-}
-
+/*
+* 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: 
+* e32\euser\epoc\arm\uc_exe.cia
+*
+*/
+
+
+#include <e32cia.h>
+#include <u32std.h>
+// Include this to get imports from User (i.e. User::Invariant and User::HandleException). 
+// This sets VISIBILITY to DEFAULT for BPABI builds.
+#include <e32std.h>
+
+extern "C" {
+
+void _xxxx_call_user_invariant();
+void _xxxx_call_user_handle_exception(void *);
+
+extern void RunThread(TBool aNotFirst, SThreadCreateInfo& aInfo);
+
+// NOTE: This MUST be the first function in this module
+__NAKED__ TInt _E32Startup()
+	{
+	// Process entry point
+	// R4 = entry reason
+	// SP points to information block
+	EKA2_ENTRY_POINT_VERSION_IDENTIFIER;	// DUMMY INSTRUCTION TO INDICATE EKA2 ENTRY POINT
+	asm("cmp r4, #%a0" : : "i" ((TInt)KModuleEntryReasonThreadInit) );
+	asm("b 1f ");				// branch over space for unique ID
+
+	asm(".word 0 ");			// loader will replace with code seg unique ID
+								// for RAM-loaded code segment
+								// MUST BE AT OFFSET 12 FROM ENTRY POINT
+
+	asm("1: ");
+	asm("movls r0, r4 ");		// r0 = aNotFirst
+	asm("movls r1, sp ");		// r1 -> parameter block
+	asm("bls RunThread ");		// process or thread init
+	asm("cmp r4, #%a0" : : "i" ((TInt)KModuleEntryReasonException) );
+//  	asm("bne " CSM_ZN4User9InvariantEv );	// invalid entry reason
+  	asm("bne _xxxx_call_user_invariant " );	// invalid entry reason
+
+	// exception entry
+	// NOTE: THUMB only works on ARMv5 and above
+	asm("mov r0, sp ");			// r0->parameter block
+	asm("ldr r4, [sp, #16]");	// r4 = saved CPSR
+	asm("tst r4, #0x20 ");		// test for THUMB
+	asm("ldrne r1, [sp, #80] ");	// r1 = saved return addr
+	asm("orrne r1, r1, #1 ");
+	asm("strne r1, [sp, #80] ");	// if THUMB, set bit 0 of return addr
+
+	asm("mov r11, sp ");		// save stack pointer
+
+	// The frame starts 84 bytes (up) from r11 i.e. CFA is r11 + 84
+	__EH_FRAME_ADDRESS(r11, 84)
+	// we can only restore callee-save values, but that's what we want if we 'leave'
+	// saved link is -8 bytes from CFA (= r11 + 0x24 + 0x20 + 0x8)
+	__EH_FRAME_SAVE1(lr, -8)
+
+	// the other callee saves start at -48 from CFA (= r11 + 0x24)
+#if 0
+	// would like to say this 
+	__EH_FRAME_SAVE1(r4-r11, -48)
+	// but the macro expansion gives rise to odd code so we do what follows
+#endif
+#ifdef __ARMCC__
+	FRAME SAVE {r4-r11}, -48
+#endif
+
+	asm("bic sp, sp, #4 ");		// align stack to 8 byte boundary
+//  	asm("bl " CSM_ZN4User15HandleExceptionEPv );
+  	asm("bl _xxxx_call_user_handle_exception ");
+	asm("add sp, r11, #16 ");	// skip exc type, exc code, FAR, FSR
+	asm("ldr r4, [sp], #4 ");	// r4 = saved CPSR
+	asm("bic r4, r4, #0x20 ");	// clear THUMB bit
+	asm("msr cpsr, r4 ");		// restore flags
+	asm("ldmia sp, {r0-r15} ");	// restore r0-r15
+
+#ifdef __ARMCC__
+#ifdef __SUPPORT_CPP_EXCEPTIONS__
+
+
+  /* It is possible no functions included in the image require
+   * a handler table. Therefore make only a weak reference to
+   * the handler table base symbol, which may be absent.
+   */
+  extern |.ARM.exidx$$Base|;
+  extern |.ARM.exidx$$Limit|;
+  extern |.ARM.extab$$Base| [WEAK];
+  extern |Image$$ER_RO$$Base|;
+  extern |Image$$ER_RO$$Limit|;
+  export |Symbian$$CPP$$Exception$$Descriptor|;
+
+|Symbian$$CPP$$Exception$$Descriptor|
+#ifdef __LEAVE_EQUALS_THROW__
+|Symbian$$eit_base|  		dcd |.ARM.exidx$$Base|;   /* index table base */
+|Symbian$$eit_limit|  		dcd |.ARM.exidx$$Limit| ;  /* index table limit */
+#endif
+#if __ARMCC_VERSION > 220000
+|Symbian$$code_seg_base| 	dcd |Image$$ER_RO$$Base| + 1 ; /* RO segment base + mark as ehabi v2 */
+|Symbian$$code_seg_limit| 	dcd |Image$$ER_RO$$Limit| ;/* RO segment limit */
+|Symbian$$reserved|		dcd 0 ; /* reserved for future use */
+#else
+|Symbian$$code_seg_base| 	dcd |Image$$ER_RO$$Base| ; /* RO segment base */
+|Symbian$$code_seg_limit| 	dcd |Image$$ER_RO$$Limit| ;/* RO segment limit */
+#endif
+
+#endif
+#endif
+
+	}
+void _xxxx_call_user_invariant() { User::Invariant(); }
+void _xxxx_call_user_handle_exception(void * arg) { User::HandleException(arg); }
+
+}
+
--- a/sbsv2/raptor/lib/flm/test/ciaabiv2_1/uc_exe.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/ciaabiv2_1/uc_exe.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,73 +1,73 @@
-/*
-* 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: 
-* e32\euser\epoc\arm\uc_exe.cpp
-*
-*/
-
-
-#include <u32std.h>
-
-
-GLREF_C TInt E32Main();
-
-extern "C" {
-
-#if defined(__GCC32__)
-typedef void (*PFV)();
-extern PFV __CTOR_LIST__[];
-extern PFV __DTOR_LIST__[];
-
-void RunThread(TBool aNotFirst, SThreadCreateInfo& aInfo)
-	{
-	SStdEpocThreadCreateInfo& cinfo = (SStdEpocThreadCreateInfo&)aInfo;
-	TInt r = UserHeap::SetupThreadHeap(aNotFirst, cinfo);
-	if (r==KErrNone)
-		{
-		if (aNotFirst)
-			r = (*cinfo.iFunction)(cinfo.iPtr);
-		else
-			{
-			// Init statics for implicitly linked DLLs
-			User::InitProcess();
-
-			// Init statics for EXE
-			TUint i=1;
-			while (__CTOR_LIST__[i])
-				(*__CTOR_LIST__[i++])();
-
-			r = E32Main();
-			}
-		}
-	User::Exit(r);
-	}
-}
-
-#elif defined(__ARMCC__)
-
-TInt CallThrdProcEntry(TInt (*aFn)(void*), void* aPtr, TInt aNotFirst);
-
-void RunThread(TBool aNotFirst, SThreadCreateInfo& aInfo)
-	{
-	SStdEpocThreadCreateInfo& cinfo = (SStdEpocThreadCreateInfo&)aInfo;
-	TInt r = UserHeap::SetupThreadHeap(aNotFirst, cinfo);
-	if (r==KErrNone)
-		r = CallThrdProcEntry(cinfo.iFunction, cinfo.iPtr, aNotFirst);
-	User::Exit(r);
-	}
-}
-
-#else
-#error not supported
-#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: 
+* e32\euser\epoc\arm\uc_exe.cpp
+*
+*/
+
+
+#include <u32std.h>
+
+
+GLREF_C TInt E32Main();
+
+extern "C" {
+
+#if defined(__GCC32__)
+typedef void (*PFV)();
+extern PFV __CTOR_LIST__[];
+extern PFV __DTOR_LIST__[];
+
+void RunThread(TBool aNotFirst, SThreadCreateInfo& aInfo)
+	{
+	SStdEpocThreadCreateInfo& cinfo = (SStdEpocThreadCreateInfo&)aInfo;
+	TInt r = UserHeap::SetupThreadHeap(aNotFirst, cinfo);
+	if (r==KErrNone)
+		{
+		if (aNotFirst)
+			r = (*cinfo.iFunction)(cinfo.iPtr);
+		else
+			{
+			// Init statics for implicitly linked DLLs
+			User::InitProcess();
+
+			// Init statics for EXE
+			TUint i=1;
+			while (__CTOR_LIST__[i])
+				(*__CTOR_LIST__[i++])();
+
+			r = E32Main();
+			}
+		}
+	User::Exit(r);
+	}
+}
+
+#elif defined(__ARMCC__)
+
+TInt CallThrdProcEntry(TInt (*aFn)(void*), void* aPtr, TInt aNotFirst);
+
+void RunThread(TBool aNotFirst, SThreadCreateInfo& aInfo)
+	{
+	SStdEpocThreadCreateInfo& cinfo = (SStdEpocThreadCreateInfo&)aInfo;
+	TInt r = UserHeap::SetupThreadHeap(aNotFirst, cinfo);
+	if (r==KErrNone)
+		r = CallThrdProcEntry(cinfo.iFunction, cinfo.iPtr, aNotFirst);
+	User::Exit(r);
+	}
+}
+
+#else
+#error not supported
+#endif
--- a/sbsv2/raptor/lib/flm/test/ciatests.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/ciatests.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,31 +1,31 @@
-#
-# 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: 
-#
-##
-# A grouping glue makefile that runs all tests
-
-## Purpose: Run test makefiles in parallel to ensure that they all work
-## Postconditions: All postconditions for all the makefiles are satisfied
-
-include $(FLMHOME)/flmtools.mk
-
-$(call vsave,ALLTARGET)
-COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/ciaabiv2_1.dll
-COMPONENT_GLUEMAKEFILES:=ciaabiv2_1/ciaabiv2_1.mk
-$(ALLTARGET):: ciatests
-ALLTARGET:=ciatests
-
-include $(FLMHOME)/grouping.flm
-$(call vrestore)
+#
+# 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: 
+#
+##
+# A grouping glue makefile that runs all tests
+
+## Purpose: Run test makefiles in parallel to ensure that they all work
+## Postconditions: All postconditions for all the makefiles are satisfied
+
+include $(FLMHOME)/flmtools.mk
+
+$(call vsave,ALLTARGET)
+COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/ciaabiv2_1.dll
+COMPONENT_GLUEMAKEFILES:=ciaabiv2_1/ciaabiv2_1.mk
+$(ALLTARGET):: ciatests
+ALLTARGET:=ciatests
+
+include $(FLMHOME)/grouping.flm
+$(call vrestore)
--- a/sbsv2/raptor/lib/flm/test/dllabiv2_1/dllabiv2_1.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/dllabiv2_1/dllabiv2_1.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,40 +1,40 @@
-#
-# 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: 
-#
-##
-## Test 1 - build an ARM E32 DLL
-## parameters relevant to the test.
-
-## Purpose: To demonstrate the building of a trivial library
-## Postconditions: dllabiv2_1.dll is written to the releasables directory
-
-# Pull in defaults for building test executables
-
-#Get the tools so we can save some variables
-include $(FLMHOME)/flmtools.mk
-
-$(call vsave,OUTPUTPATH SOURCEPATH CDEFS SYSTEMINCLUDE)
-include $(FLMTESTHOME)/dllabiv2_defaults.mk
-
-TARGET:=dllabiv2_1
-CDEFS:=$(CDEFS) __TESTNAME__=\"dllabiv2_1\"
-OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)
-SOURCEPATH:=$(SOURCEPATH)/dllabiv2_1
-SOURCEFILES:=$(SOURCEPATH)/test.cpp
-
-include $(FLMHOME)/$(FLM)
-
-# Restore the variables we modified
-$(call vrestore)
+#
+# 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: 
+#
+##
+## Test 1 - build an ARM E32 DLL
+## parameters relevant to the test.
+
+## Purpose: To demonstrate the building of a trivial library
+## Postconditions: dllabiv2_1.dll is written to the releasables directory
+
+# Pull in defaults for building test executables
+
+#Get the tools so we can save some variables
+include $(FLMHOME)/flmtools.mk
+
+$(call vsave,OUTPUTPATH SOURCEPATH CDEFS SYSTEMINCLUDE)
+include $(FLMTESTHOME)/dllabiv2_defaults.mk
+
+TARGET:=dllabiv2_1
+CDEFS:=$(CDEFS) __TESTNAME__=\"dllabiv2_1\"
+OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)
+SOURCEPATH:=$(SOURCEPATH)/dllabiv2_1
+SOURCEFILES:=$(SOURCEPATH)/test.cpp
+
+include $(FLMHOME)/$(FLM)
+
+# Restore the variables we modified
+$(call vrestore)
--- a/sbsv2/raptor/lib/flm/test/dllabiv2_1/test.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/dllabiv2_1/test.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,24 +1,24 @@
-/*
-* 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: 
-*
-*/
-#include "e32def.h" // intentional  include
-
-char test[]=__TESTNAME__;
-
-TInt E32Main()
-{
-	return 0;
-}
+/*
+* 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: 
+*
+*/
+#include "e32def.h" // intentional  include
+
+char test[]=__TESTNAME__;
+
+TInt E32Main()
+{
+	return 0;
+}
--- a/sbsv2/raptor/lib/flm/test/dllabiv2_defaults.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/dllabiv2_defaults.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,45 +1,45 @@
-#
-# 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: 
-#
-##
-# Defaults for ABIv2 EXE build tests
-
-## Purpose: To enable all test makefiles to be updated rapidly
-
-
-include $(FLMHOME)/e32abiv2.mk
-
-DEBUG:=1
-
-CAPABILITY:=LocalServices ReadDeviceData ReadUserData
-UID1:=0x1000007a
-UID2:=0x100039ce
-UID3:=0x000001
-SID:=0x10003a5c
-EXETARGET:=
-MAPFILENAME:=
-BMPS:=
-EPOCDATA:=
-
-VARIANTARCH:=ARMV5
-FULLVARIANTPATH=$(VARIANTARCH)/$(VARIANTTYPE)
-STATIC_LIBS_PATH:=/usr/local/ARM/RVCT/Data/2.2/308/lib/armlib
-RUNTIME_LIBS_PATH=$(RELEASEPATH)/$(VARIANTARCH)/LIB
-RELEASEPATH:=$(EPOCROOT)/epoc32/release
-FLM:=e32abiv2dll.flm
-CDEFS:=$(CDEFS) __DLL__
-
-
-
+#
+# 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: 
+#
+##
+# Defaults for ABIv2 EXE build tests
+
+## Purpose: To enable all test makefiles to be updated rapidly
+
+
+include $(FLMHOME)/e32abiv2.mk
+
+DEBUG:=1
+
+CAPABILITY:=LocalServices ReadDeviceData ReadUserData
+UID1:=0x1000007a
+UID2:=0x100039ce
+UID3:=0x000001
+SID:=0x10003a5c
+EXETARGET:=
+MAPFILENAME:=
+BMPS:=
+EPOCDATA:=
+
+VARIANTARCH:=ARMV5
+FULLVARIANTPATH=$(VARIANTARCH)/$(VARIANTTYPE)
+STATIC_LIBS_PATH:=/usr/local/ARM/RVCT/Data/2.2/308/lib/armlib
+RUNTIME_LIBS_PATH=$(RELEASEPATH)/$(VARIANTARCH)/LIB
+RELEASEPATH:=$(EPOCROOT)/epoc32/release
+FLM:=e32abiv2dll.flm
+CDEFS:=$(CDEFS) __DLL__
+
+
+
--- a/sbsv2/raptor/lib/flm/test/dllbasictests.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/dllbasictests.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,31 +1,31 @@
-#
-# 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: 
-#
-##
-# A grouping glue makefile that runs all tests
-
-## Purpose: Run test makefiles in parallel to ensure that they all work
-## Postconditions: All postconditions for all the makefiles are satisfied
-
-include $(FLMHOME)/flmtools.mk
-
-$(call vsave,ALLTARGET OUTPUTPATH)
-COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/dllabiv2_1.dll
-COMPONENT_GLUEMAKEFILES:=dllabiv2_1/dllabiv2_1.mk 
-$(ALLTARGET):: dllbasictests
-ALLTARGET:=dllbasictests
-
-include $(FLMHOME)/grouping.flm
-$(call vrestore)
+#
+# 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: 
+#
+##
+# A grouping glue makefile that runs all tests
+
+## Purpose: Run test makefiles in parallel to ensure that they all work
+## Postconditions: All postconditions for all the makefiles are satisfied
+
+include $(FLMHOME)/flmtools.mk
+
+$(call vsave,ALLTARGET OUTPUTPATH)
+COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/dllabiv2_1.dll
+COMPONENT_GLUEMAKEFILES:=dllabiv2_1/dllabiv2_1.mk 
+$(ALLTARGET):: dllbasictests
+ALLTARGET:=dllbasictests
+
+include $(FLMHOME)/grouping.flm
+$(call vrestore)
--- a/sbsv2/raptor/lib/flm/test/environment/make/test_variable_restore.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/environment/make/test_variable_restore.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,97 +1,97 @@
-#
-# 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: 
-#
-# Makefile that demonstrates the effect of state saving macros
-# when used across multiple FLM calls
-
-#
-# basically for testing the stack.mk amkefile fragmemt
-# Which chould be inluded by flmtools.mk
-#
-
-
-.PHONY: stack-debug
-
-OUTPUTPATH:=_PRE_OUTPUTPATH_
-SOURCEPATH:=_PRE_SOURCEPATH_
-
-COMMA:= ,
-EMPTY:=
-SPACE:= $(EMPTY) $(EMPTY)
-
-
-include $(FLMHOME)/flmtools.mk
-
-OUTPUTPATH:=ORIGINAL_OUTPUTPATH OP2 OP3
-SOURCEPATH:=ORIGINAL_SOURCEPATH SP2 SP3
-
-###############################################################################
-# Rules for testing
-.PHONY: all
-
-all: stack-debug stack-debug2 stack-debug3
-	@echo "FLM stack TEST SUCCEEDED"
-
-.PHONY: stack-debug
-stack-debug: VARIABLE_STACK_NAME:=$(VARIABLE_STACK_NAME)
-stack-debug: OUTPUTPATH:=$(OUTPUTPATH)
-stack-debug: SOURCEPATH:=$(SOURCEPATH)
-
-stack-debug:
-	@echo NAME=\"$(VARIABLE_STACK_NAME)\"
-	@echo "	Stack Name: \"$(VARIABLE_STACK_NAME)\""
-	@echo "	Stack contents: \"$($(VARIABLE_STACK_NAME)$)\""
-	@echo "Original Parameters iprior to 'FLM Call': "
-	@echo "	OUTPUTPATH: "$(OUTPUTPATH)
-	@echo "	SOURCEPATH: "$(SOURCEPATH)
-	[ "$(OUTPUTPATH)" == "ORIGINAL_OUTPUTPATH OP2 OP3" ]
-	[ "$(SOURCEPATH)" == "ORIGINAL_SOURCEPATH SP2 SP3" ]
-
-
-$(call vsave,OUTPUTPATH SOURCEPATH)
-OUTPUTPATH:=MODIFIED OUTPUTPATH
-SOURCEPATH:=MODIFIED OUTPUTPATH
-
-
-
-.PHONY: stack-debug2
-stack-debug2: VARIABLE_STACK_NAME:=$(VARIABLE_STACK_NAME)
-stack-debug2: OUTPUTPATH:=$(OUTPUTPATH)
-stack-debug2: SOURCEPATH:=$(SOURCEPATH)
-stack-debug2:
-	@echo "--------------------"
-	@echo "	Stack Name: \"$(VARIABLE_STACK_NAME)\""
-	@echo "Parameters after 'FLM Call': "
-	@echo "	OUTPUTPATH: "$(OUTPUTPATH)
-	@echo "	SOURCEPATH: "$(SOURCEPATH)
-	[ "$(OUTPUTPATH)" == "MODIFIED OUTPUTPATH" ]
-	[ "$(SOURCEPATH)" == "MODIFIED OUTPUTPATH" ]
-
-
-$(call vrestore)
-
-
-.PHONY: stack-debug3
-stack-debug3: VARIABLE_STACK_NAME:=$(VARIABLE_STACK_NAME)
-stack-debug3: OUTPUTPATH:=$(OUTPUTPATH)
-stack-debug3: SOURCEPATH:=$(SOURCEPATH)
-stack-debug3:
-	@echo "--------------------"
-	@echo "	Stack Name: \"$(VARIABLE_STACK_NAME)\""
-	@echo "Parameters after restore: "
-	@echo "	OUTPUTPATH: "$(OUTPUTPATH)
-	@echo "	SOURCEPATH: "$(SOURCEPATH)
-	[ "$(OUTPUTPATH)" == "ORIGINAL_OUTPUTPATH OP2 OP3" ]
-	[ "$(SOURCEPATH)" == "ORIGINAL_SOURCEPATH SP2 SP3" ]
+#
+# 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: 
+#
+# Makefile that demonstrates the effect of state saving macros
+# when used across multiple FLM calls
+
+#
+# basically for testing the stack.mk amkefile fragmemt
+# Which chould be inluded by flmtools.mk
+#
+
+
+.PHONY: stack-debug
+
+OUTPUTPATH:=_PRE_OUTPUTPATH_
+SOURCEPATH:=_PRE_SOURCEPATH_
+
+COMMA:= ,
+EMPTY:=
+SPACE:= $(EMPTY) $(EMPTY)
+
+
+include $(FLMHOME)/flmtools.mk
+
+OUTPUTPATH:=ORIGINAL_OUTPUTPATH OP2 OP3
+SOURCEPATH:=ORIGINAL_SOURCEPATH SP2 SP3
+
+###############################################################################
+# Rules for testing
+.PHONY: all
+
+all: stack-debug stack-debug2 stack-debug3
+	@echo "FLM stack TEST SUCCEEDED"
+
+.PHONY: stack-debug
+stack-debug: VARIABLE_STACK_NAME:=$(VARIABLE_STACK_NAME)
+stack-debug: OUTPUTPATH:=$(OUTPUTPATH)
+stack-debug: SOURCEPATH:=$(SOURCEPATH)
+
+stack-debug:
+	@echo NAME=\"$(VARIABLE_STACK_NAME)\"
+	@echo "	Stack Name: \"$(VARIABLE_STACK_NAME)\""
+	@echo "	Stack contents: \"$($(VARIABLE_STACK_NAME)$)\""
+	@echo "Original Parameters iprior to 'FLM Call': "
+	@echo "	OUTPUTPATH: "$(OUTPUTPATH)
+	@echo "	SOURCEPATH: "$(SOURCEPATH)
+	[ "$(OUTPUTPATH)" == "ORIGINAL_OUTPUTPATH OP2 OP3" ]
+	[ "$(SOURCEPATH)" == "ORIGINAL_SOURCEPATH SP2 SP3" ]
+
+
+$(call vsave,OUTPUTPATH SOURCEPATH)
+OUTPUTPATH:=MODIFIED OUTPUTPATH
+SOURCEPATH:=MODIFIED OUTPUTPATH
+
+
+
+.PHONY: stack-debug2
+stack-debug2: VARIABLE_STACK_NAME:=$(VARIABLE_STACK_NAME)
+stack-debug2: OUTPUTPATH:=$(OUTPUTPATH)
+stack-debug2: SOURCEPATH:=$(SOURCEPATH)
+stack-debug2:
+	@echo "--------------------"
+	@echo "	Stack Name: \"$(VARIABLE_STACK_NAME)\""
+	@echo "Parameters after 'FLM Call': "
+	@echo "	OUTPUTPATH: "$(OUTPUTPATH)
+	@echo "	SOURCEPATH: "$(SOURCEPATH)
+	[ "$(OUTPUTPATH)" == "MODIFIED OUTPUTPATH" ]
+	[ "$(SOURCEPATH)" == "MODIFIED OUTPUTPATH" ]
+
+
+$(call vrestore)
+
+
+.PHONY: stack-debug3
+stack-debug3: VARIABLE_STACK_NAME:=$(VARIABLE_STACK_NAME)
+stack-debug3: OUTPUTPATH:=$(OUTPUTPATH)
+stack-debug3: SOURCEPATH:=$(SOURCEPATH)
+stack-debug3:
+	@echo "--------------------"
+	@echo "	Stack Name: \"$(VARIABLE_STACK_NAME)\""
+	@echo "Parameters after restore: "
+	@echo "	OUTPUTPATH: "$(OUTPUTPATH)
+	@echo "	SOURCEPATH: "$(SOURCEPATH)
+	[ "$(OUTPUTPATH)" == "ORIGINAL_OUTPUTPATH OP2 OP3" ]
+	[ "$(SOURCEPATH)" == "ORIGINAL_SOURCEPATH SP2 SP3" ]
--- a/sbsv2/raptor/lib/flm/test/environment/pvm/pvmtest.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/environment/pvm/pvmtest.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,25 +1,25 @@
-#
-# 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: 
-#
-
-.PHONY: all one two
-
-all: one two
-
-one:
-	@echo ARCH=`$(PVM_ROOT)/lib/pvmgetarch`/`hostname`; hostname; /usr/local/ARM/RVCT/Programs/2.2/308/linux-pentium/armcc 
-
-two:
-	@echo ARCH=`$(PVM_ROOT)/lib/pvmgetarch`/`hostname`; hostname; /usr/local/ARM/RVCT/Programs/2.2/308/linux-pentium/armcc
+#
+# 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: 
+#
+
+.PHONY: all one two
+
+all: one two
+
+one:
+	@echo ARCH=`$(PVM_ROOT)/lib/pvmgetarch`/`hostname`; hostname; /usr/local/ARM/RVCT/Programs/2.2/308/linux-pentium/armcc 
+
+two:
+	@echo ARCH=`$(PVM_ROOT)/lib/pvmgetarch`/`hostname`; hostname; /usr/local/ARM/RVCT/Programs/2.2/308/linux-pentium/armcc
--- a/sbsv2/raptor/lib/flm/test/exeabiv2_1/exeabiv2_1.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/exeabiv2_1/exeabiv2_1.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,42 +1,42 @@
-#
-# 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: 
-#
-##
-## Test 1 - build an ARM E32 EXE on Linux
-## parameters relevant to the test.
-
-## Purpose: To demonstrate use of 1 call to a basic flm with one input file
-## Postconditions: test1.exe is written to the output directory $OUTPUTPATH/test1/test1.exe:
-
-# Pull tools
-include $(FLMHOME)/flmtools.mk
-
-
-$(call vsave,OUTPUTPATH SOURCEPATH CDEFS SYSTEMINCLUDE)
-# Pull in defaults for building test executables
-include $(FLMTESTHOME)/exeabiv2_defaults.mk
-
-TARGET:=exeabiv2_1
-CDEFS:=$(CDEFS) __TESTNAME__=\"exeabiv2_1\"
-OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)
-SOURCEPATH:=$(SOURCEPATH)/exeabiv2_1
-SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(FLMTESTHOME)/include
-SOURCEFILES:=$(SOURCEPATH)/test.cpp
-UID3:=0x000001
-
-
-include $(FLMHOME)/$(FLM)
-
-$(call vrestore)
+#
+# 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: 
+#
+##
+## Test 1 - build an ARM E32 EXE on Linux
+## parameters relevant to the test.
+
+## Purpose: To demonstrate use of 1 call to a basic flm with one input file
+## Postconditions: test1.exe is written to the output directory $OUTPUTPATH/test1/test1.exe:
+
+# Pull tools
+include $(FLMHOME)/flmtools.mk
+
+
+$(call vsave,OUTPUTPATH SOURCEPATH CDEFS SYSTEMINCLUDE)
+# Pull in defaults for building test executables
+include $(FLMTESTHOME)/exeabiv2_defaults.mk
+
+TARGET:=exeabiv2_1
+CDEFS:=$(CDEFS) __TESTNAME__=\"exeabiv2_1\"
+OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)
+SOURCEPATH:=$(SOURCEPATH)/exeabiv2_1
+SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(FLMTESTHOME)/include
+SOURCEFILES:=$(SOURCEPATH)/test.cpp
+UID3:=0x000001
+
+
+include $(FLMHOME)/$(FLM)
+
+$(call vrestore)
--- a/sbsv2/raptor/lib/flm/test/exeabiv2_1/test.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/exeabiv2_1/test.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,24 +1,24 @@
-/*
-* 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: 
-*
-*/
-#include "e32def.h" // intentional  include
-
-char test[]=__TESTNAME__;
-
-TInt E32Main()
-{
-	return 0;
-}
+/*
+* 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: 
+*
+*/
+#include "e32def.h" // intentional  include
+
+char test[]=__TESTNAME__;
+
+TInt E32Main()
+{
+	return 0;
+}
--- a/sbsv2/raptor/lib/flm/test/exeabiv2_2/exeabiv2_2.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/exeabiv2_2/exeabiv2_2.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,47 +1,47 @@
-#
-# 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: 
-#
-##
-## Test 1 - build an ARM E32 EXE on Linux
-## parameters relevant to the test.
-##
-
-
-## Purpose:
-## to demonstrate use of 1 call to a basic flm with two input files
-## postconditions:
-## test2.exe is written to the output directory $OUTPUTPATH/test2/test2.exe
-## test1.o and test2.o are generated in $OUTPUTPATH/test1/test1.o and $OUTPUTPATH/test2/test2.exe
-
-
-# Pull tools
-include $(FLMHOME)/flmtools.mk
-
-$(call vsave,OUTPUTPATH SOURCEPATH CDEFS SYSTEMINCLUDE)
-# Pull in defaults for building test executables
-include $(FLMTESTHOME)/exeabiv2_defaults.mk
-
-
-TARGET:=exeabiv2_2
-CDEFS:=$(CDEFS) __TESTNAME__=\"exeabiv2_2\"
-OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)
-SOURCEPATH:=$(SOURCEPATH)/exeabiv2_2
-SOURCEFILES:=$(SOURCEPATH)/test.cpp $(SOURCEPATH)/test_function.cpp
-SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(FLMTESTHOME)/include
-UID3:=0x000002
-
-include $(FLMHOME)/$(FLM)
-
-$(call vrestore)
+#
+# 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: 
+#
+##
+## Test 1 - build an ARM E32 EXE on Linux
+## parameters relevant to the test.
+##
+
+
+## Purpose:
+## to demonstrate use of 1 call to a basic flm with two input files
+## postconditions:
+## test2.exe is written to the output directory $OUTPUTPATH/test2/test2.exe
+## test1.o and test2.o are generated in $OUTPUTPATH/test1/test1.o and $OUTPUTPATH/test2/test2.exe
+
+
+# Pull tools
+include $(FLMHOME)/flmtools.mk
+
+$(call vsave,OUTPUTPATH SOURCEPATH CDEFS SYSTEMINCLUDE)
+# Pull in defaults for building test executables
+include $(FLMTESTHOME)/exeabiv2_defaults.mk
+
+
+TARGET:=exeabiv2_2
+CDEFS:=$(CDEFS) __TESTNAME__=\"exeabiv2_2\"
+OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)
+SOURCEPATH:=$(SOURCEPATH)/exeabiv2_2
+SOURCEFILES:=$(SOURCEPATH)/test.cpp $(SOURCEPATH)/test_function.cpp
+SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(FLMTESTHOME)/include
+UID3:=0x000002
+
+include $(FLMHOME)/$(FLM)
+
+$(call vrestore)
--- a/sbsv2/raptor/lib/flm/test/exeabiv2_2/test.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/exeabiv2_2/test.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,27 +1,27 @@
-/*
-* 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: 
-*
-*/
-
-#include <e32def.h>
-
-int i=1;
-
-extern int function_in_test2(void);
-TInt E32Main(void)
-{
-	function_in_test2();
-	return 0;
-}
+/*
+* 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: 
+*
+*/
+
+#include <e32def.h>
+
+int i=1;
+
+extern int function_in_test2(void);
+TInt E32Main(void)
+{
+	function_in_test2();
+	return 0;
+}
--- a/sbsv2/raptor/lib/flm/test/exeabiv2_2/test_function.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/exeabiv2_2/test_function.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,27 +1,27 @@
-/*
-* 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: 
-*
-*/
-
-int function_in_test2(void)
-{
-	int x,y;
-	x=20+30* 10-1;
-	y=x*4;
-
-	x=y+1;
-
-	return 0;
-}
+/*
+* 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: 
+*
+*/
+
+int function_in_test2(void)
+{
+	int x,y;
+	x=20+30* 10-1;
+	y=x*4;
+
+	x=y+1;
+
+	return 0;
+}
--- a/sbsv2/raptor/lib/flm/test/exeabiv2_3/exeabiv2_3.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/exeabiv2_3/exeabiv2_3.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,46 +1,46 @@
-#
-# 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: 
-#
-##
-## Test 1 - build an ARM E32 EXE on Linux
-## parameters relevant to the test.
-##
-
-
-## Purpose:
-## This is used to gauge perfomance 
-## At least one "large" input file is built
-## The input file has no dependencies so it really is just something for the compiler to "chew"
-
-
-# Pull tools
-include $(FLMHOME)/flmtools.mk
-
-$(call vsave,OUTPUTPATH SOURCEPATH CDEFS SYSTEMINCLUDE)
-# Pull in defaults for building test executables
-include $(FLMTESTHOME)/exeabiv2_defaults.mk
-
-
-TARGET:=exeabiv2_3
-CDEFS:=$(CDEFS) __TESTNAME__=\"exeabiv2_3\"
-OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)
-SOURCEPATH:=$(SOURCEPATH)/exeabiv2_3
-SOURCEFILES:=$(SOURCEPATH)/test.cpp $(SOURCEPATH)/test_big.cpp
-SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(FLMTESTHOME)/include
-UID3:=0x000003
-
-include $(FLMHOME)/$(FLM)
-
-$(call vrestore)
+#
+# 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: 
+#
+##
+## Test 1 - build an ARM E32 EXE on Linux
+## parameters relevant to the test.
+##
+
+
+## Purpose:
+## This is used to gauge perfomance 
+## At least one "large" input file is built
+## The input file has no dependencies so it really is just something for the compiler to "chew"
+
+
+# Pull tools
+include $(FLMHOME)/flmtools.mk
+
+$(call vsave,OUTPUTPATH SOURCEPATH CDEFS SYSTEMINCLUDE)
+# Pull in defaults for building test executables
+include $(FLMTESTHOME)/exeabiv2_defaults.mk
+
+
+TARGET:=exeabiv2_3
+CDEFS:=$(CDEFS) __TESTNAME__=\"exeabiv2_3\"
+OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)
+SOURCEPATH:=$(SOURCEPATH)/exeabiv2_3
+SOURCEFILES:=$(SOURCEPATH)/test.cpp $(SOURCEPATH)/test_big.cpp
+SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(FLMTESTHOME)/include
+UID3:=0x000003
+
+include $(FLMHOME)/$(FLM)
+
+$(call vrestore)
--- a/sbsv2/raptor/lib/flm/test/exeabiv2_3/test_big.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/exeabiv2_3/test_big.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,2045 +1,2045 @@
-/*
-* 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: 
-*
-*/
-/* 
-This is jsut some "compiler fibre" for the compiler to chew
-on as part of a compilation performace test
-*/
-
-#define FUNC(VARIABLE)	\
-int function_##VARIABLE(void)	\
-{	\
-	int x,y,z;	\
-	x=VARIABLE+30* 10-1;	\
-	y=x*4;	\
-	\
-	\
-	x=y+1;	\
-	\
-	int a[VARIABLE];	\
-	\
-	\
-	\
-	for (z=0; z < 1000+VARIABLE; z++)	\
-	{	\
-		x+=a[z];		\
-	}	\
-	\
-	return x;	\
-}
-
-
-
-FUNC(1)
-FUNC(2)
-FUNC(3)
-FUNC(4)
-FUNC(5)
-FUNC(6)
-FUNC(7)
-FUNC(8)
-FUNC(9)
-FUNC(10)
-FUNC(11)
-FUNC(12)
-FUNC(13)
-FUNC(14)
-FUNC(15)
-FUNC(16)
-FUNC(17)
-FUNC(18)
-FUNC(19)
-FUNC(20)
-FUNC(21)
-FUNC(22)
-FUNC(23)
-FUNC(24)
-FUNC(25)
-FUNC(26)
-FUNC(27)
-FUNC(28)
-FUNC(29)
-FUNC(30)
-FUNC(31)
-FUNC(32)
-FUNC(33)
-FUNC(34)
-FUNC(35)
-FUNC(36)
-FUNC(37)
-FUNC(38)
-FUNC(39)
-FUNC(40)
-FUNC(41)
-FUNC(42)
-FUNC(43)
-FUNC(44)
-FUNC(45)
-FUNC(46)
-FUNC(47)
-FUNC(48)
-FUNC(49)
-FUNC(50)
-FUNC(51)
-FUNC(52)
-FUNC(53)
-FUNC(54)
-FUNC(55)
-FUNC(56)
-FUNC(57)
-FUNC(58)
-FUNC(59)
-FUNC(60)
-FUNC(61)
-FUNC(62)
-FUNC(63)
-FUNC(64)
-FUNC(65)
-FUNC(66)
-FUNC(67)
-FUNC(68)
-FUNC(69)
-FUNC(70)
-FUNC(71)
-FUNC(72)
-FUNC(73)
-FUNC(74)
-FUNC(75)
-FUNC(76)
-FUNC(77)
-FUNC(78)
-FUNC(79)
-FUNC(80)
-FUNC(81)
-FUNC(82)
-FUNC(83)
-FUNC(84)
-FUNC(85)
-FUNC(86)
-FUNC(87)
-FUNC(88)
-FUNC(89)
-FUNC(90)
-FUNC(91)
-FUNC(92)
-FUNC(93)
-FUNC(94)
-FUNC(95)
-FUNC(96)
-FUNC(97)
-FUNC(98)
-FUNC(99)
-FUNC(100)
-FUNC(101)
-FUNC(102)
-FUNC(103)
-FUNC(104)
-FUNC(105)
-FUNC(106)
-FUNC(107)
-FUNC(108)
-FUNC(109)
-FUNC(110)
-FUNC(111)
-FUNC(112)
-FUNC(113)
-FUNC(114)
-FUNC(115)
-FUNC(116)
-FUNC(117)
-FUNC(118)
-FUNC(119)
-FUNC(120)
-FUNC(121)
-FUNC(122)
-FUNC(123)
-FUNC(124)
-FUNC(125)
-FUNC(126)
-FUNC(127)
-FUNC(128)
-FUNC(129)
-FUNC(130)
-FUNC(131)
-FUNC(132)
-FUNC(133)
-FUNC(134)
-FUNC(135)
-FUNC(136)
-FUNC(137)
-FUNC(138)
-FUNC(139)
-FUNC(140)
-FUNC(141)
-FUNC(142)
-FUNC(143)
-FUNC(144)
-FUNC(145)
-FUNC(146)
-FUNC(147)
-FUNC(148)
-FUNC(149)
-FUNC(150)
-FUNC(151)
-FUNC(152)
-FUNC(153)
-FUNC(154)
-FUNC(155)
-FUNC(156)
-FUNC(157)
-FUNC(158)
-FUNC(159)
-FUNC(160)
-FUNC(161)
-FUNC(162)
-FUNC(163)
-FUNC(164)
-FUNC(165)
-FUNC(166)
-FUNC(167)
-FUNC(168)
-FUNC(169)
-FUNC(170)
-FUNC(171)
-FUNC(172)
-FUNC(173)
-FUNC(174)
-FUNC(175)
-FUNC(176)
-FUNC(177)
-FUNC(178)
-FUNC(179)
-FUNC(180)
-FUNC(181)
-FUNC(182)
-FUNC(183)
-FUNC(184)
-FUNC(185)
-FUNC(186)
-FUNC(187)
-FUNC(188)
-FUNC(189)
-FUNC(190)
-FUNC(191)
-FUNC(192)
-FUNC(193)
-FUNC(194)
-FUNC(195)
-FUNC(196)
-FUNC(197)
-FUNC(198)
-FUNC(199)
-FUNC(200)
-FUNC(201)
-FUNC(202)
-FUNC(203)
-FUNC(204)
-FUNC(205)
-FUNC(206)
-FUNC(207)
-FUNC(208)
-FUNC(209)
-FUNC(210)
-FUNC(211)
-FUNC(212)
-FUNC(213)
-FUNC(214)
-FUNC(215)
-FUNC(216)
-FUNC(217)
-FUNC(218)
-FUNC(219)
-FUNC(220)
-FUNC(221)
-FUNC(222)
-FUNC(223)
-FUNC(224)
-FUNC(225)
-FUNC(226)
-FUNC(227)
-FUNC(228)
-FUNC(229)
-FUNC(230)
-FUNC(231)
-FUNC(232)
-FUNC(233)
-FUNC(234)
-FUNC(235)
-FUNC(236)
-FUNC(237)
-FUNC(238)
-FUNC(239)
-FUNC(240)
-FUNC(241)
-FUNC(242)
-FUNC(243)
-FUNC(244)
-FUNC(245)
-FUNC(246)
-FUNC(247)
-FUNC(248)
-FUNC(249)
-FUNC(250)
-FUNC(251)
-FUNC(252)
-FUNC(253)
-FUNC(254)
-FUNC(255)
-FUNC(256)
-FUNC(257)
-FUNC(258)
-FUNC(259)
-FUNC(260)
-FUNC(261)
-FUNC(262)
-FUNC(263)
-FUNC(264)
-FUNC(265)
-FUNC(266)
-FUNC(267)
-FUNC(268)
-FUNC(269)
-FUNC(270)
-FUNC(271)
-FUNC(272)
-FUNC(273)
-FUNC(274)
-FUNC(275)
-FUNC(276)
-FUNC(277)
-FUNC(278)
-FUNC(279)
-FUNC(280)
-FUNC(281)
-FUNC(282)
-FUNC(283)
-FUNC(284)
-FUNC(285)
-FUNC(286)
-FUNC(287)
-FUNC(288)
-FUNC(289)
-FUNC(290)
-FUNC(291)
-FUNC(292)
-FUNC(293)
-FUNC(294)
-FUNC(295)
-FUNC(296)
-FUNC(297)
-FUNC(298)
-FUNC(299)
-FUNC(300)
-FUNC(301)
-FUNC(302)
-FUNC(303)
-FUNC(304)
-FUNC(305)
-FUNC(306)
-FUNC(307)
-FUNC(308)
-FUNC(309)
-FUNC(310)
-FUNC(311)
-FUNC(312)
-FUNC(313)
-FUNC(314)
-FUNC(315)
-FUNC(316)
-FUNC(317)
-FUNC(318)
-FUNC(319)
-FUNC(320)
-FUNC(321)
-FUNC(322)
-FUNC(323)
-FUNC(324)
-FUNC(325)
-FUNC(326)
-FUNC(327)
-FUNC(328)
-FUNC(329)
-FUNC(330)
-FUNC(331)
-FUNC(332)
-FUNC(333)
-FUNC(334)
-FUNC(335)
-FUNC(336)
-FUNC(337)
-FUNC(338)
-FUNC(339)
-FUNC(340)
-FUNC(341)
-FUNC(342)
-FUNC(343)
-FUNC(344)
-FUNC(345)
-FUNC(346)
-FUNC(347)
-FUNC(348)
-FUNC(349)
-FUNC(350)
-FUNC(351)
-FUNC(352)
-FUNC(353)
-FUNC(354)
-FUNC(355)
-FUNC(356)
-FUNC(357)
-FUNC(358)
-FUNC(359)
-FUNC(360)
-FUNC(361)
-FUNC(362)
-FUNC(363)
-FUNC(364)
-FUNC(365)
-FUNC(366)
-FUNC(367)
-FUNC(368)
-FUNC(369)
-FUNC(370)
-FUNC(371)
-FUNC(372)
-FUNC(373)
-FUNC(374)
-FUNC(375)
-FUNC(376)
-FUNC(377)
-FUNC(378)
-FUNC(379)
-FUNC(380)
-FUNC(381)
-FUNC(382)
-FUNC(383)
-FUNC(384)
-FUNC(385)
-FUNC(386)
-FUNC(387)
-FUNC(388)
-FUNC(389)
-FUNC(390)
-FUNC(391)
-FUNC(392)
-FUNC(393)
-FUNC(394)
-FUNC(395)
-FUNC(396)
-FUNC(397)
-FUNC(398)
-FUNC(399)
-FUNC(400)
-FUNC(401)
-FUNC(402)
-FUNC(403)
-FUNC(404)
-FUNC(405)
-FUNC(406)
-FUNC(407)
-FUNC(408)
-FUNC(409)
-FUNC(410)
-FUNC(411)
-FUNC(412)
-FUNC(413)
-FUNC(414)
-FUNC(415)
-FUNC(416)
-FUNC(417)
-FUNC(418)
-FUNC(419)
-FUNC(420)
-FUNC(421)
-FUNC(422)
-FUNC(423)
-FUNC(424)
-FUNC(425)
-FUNC(426)
-FUNC(427)
-FUNC(428)
-FUNC(429)
-FUNC(430)
-FUNC(431)
-FUNC(432)
-FUNC(433)
-FUNC(434)
-FUNC(435)
-FUNC(436)
-FUNC(437)
-FUNC(438)
-FUNC(439)
-FUNC(440)
-FUNC(441)
-FUNC(442)
-FUNC(443)
-FUNC(444)
-FUNC(445)
-FUNC(446)
-FUNC(447)
-FUNC(448)
-FUNC(449)
-FUNC(450)
-FUNC(451)
-FUNC(452)
-FUNC(453)
-FUNC(454)
-FUNC(455)
-FUNC(456)
-FUNC(457)
-FUNC(458)
-FUNC(459)
-FUNC(460)
-FUNC(461)
-FUNC(462)
-FUNC(463)
-FUNC(464)
-FUNC(465)
-FUNC(466)
-FUNC(467)
-FUNC(468)
-FUNC(469)
-FUNC(470)
-FUNC(471)
-FUNC(472)
-FUNC(473)
-FUNC(474)
-FUNC(475)
-FUNC(476)
-FUNC(477)
-FUNC(478)
-FUNC(479)
-FUNC(480)
-FUNC(481)
-FUNC(482)
-FUNC(483)
-FUNC(484)
-FUNC(485)
-FUNC(486)
-FUNC(487)
-FUNC(488)
-FUNC(489)
-FUNC(490)
-FUNC(491)
-FUNC(492)
-FUNC(493)
-FUNC(494)
-FUNC(495)
-FUNC(496)
-FUNC(497)
-FUNC(498)
-FUNC(499)
-FUNC(500)
-FUNC(501)
-FUNC(502)
-FUNC(503)
-FUNC(504)
-FUNC(505)
-FUNC(506)
-FUNC(507)
-FUNC(508)
-FUNC(509)
-FUNC(510)
-FUNC(511)
-FUNC(512)
-FUNC(513)
-FUNC(514)
-FUNC(515)
-FUNC(516)
-FUNC(517)
-FUNC(518)
-FUNC(519)
-FUNC(520)
-FUNC(521)
-FUNC(522)
-FUNC(523)
-FUNC(524)
-FUNC(525)
-FUNC(526)
-FUNC(527)
-FUNC(528)
-FUNC(529)
-FUNC(530)
-FUNC(531)
-FUNC(532)
-FUNC(533)
-FUNC(534)
-FUNC(535)
-FUNC(536)
-FUNC(537)
-FUNC(538)
-FUNC(539)
-FUNC(540)
-FUNC(541)
-FUNC(542)
-FUNC(543)
-FUNC(544)
-FUNC(545)
-FUNC(546)
-FUNC(547)
-FUNC(548)
-FUNC(549)
-FUNC(550)
-FUNC(551)
-FUNC(552)
-FUNC(553)
-FUNC(554)
-FUNC(555)
-FUNC(556)
-FUNC(557)
-FUNC(558)
-FUNC(559)
-FUNC(560)
-FUNC(561)
-FUNC(562)
-FUNC(563)
-FUNC(564)
-FUNC(565)
-FUNC(566)
-FUNC(567)
-FUNC(568)
-FUNC(569)
-FUNC(570)
-FUNC(571)
-FUNC(572)
-FUNC(573)
-FUNC(574)
-FUNC(575)
-FUNC(576)
-FUNC(577)
-FUNC(578)
-FUNC(579)
-FUNC(580)
-FUNC(581)
-FUNC(582)
-FUNC(583)
-FUNC(584)
-FUNC(585)
-FUNC(586)
-FUNC(587)
-FUNC(588)
-FUNC(589)
-FUNC(590)
-FUNC(591)
-FUNC(592)
-FUNC(593)
-FUNC(594)
-FUNC(595)
-FUNC(596)
-FUNC(597)
-FUNC(598)
-FUNC(599)
-FUNC(600)
-FUNC(601)
-FUNC(602)
-FUNC(603)
-FUNC(604)
-FUNC(605)
-FUNC(606)
-FUNC(607)
-FUNC(608)
-FUNC(609)
-FUNC(610)
-FUNC(611)
-FUNC(612)
-FUNC(613)
-FUNC(614)
-FUNC(615)
-FUNC(616)
-FUNC(617)
-FUNC(618)
-FUNC(619)
-FUNC(620)
-FUNC(621)
-FUNC(622)
-FUNC(623)
-FUNC(624)
-FUNC(625)
-FUNC(626)
-FUNC(627)
-FUNC(628)
-FUNC(629)
-FUNC(630)
-FUNC(631)
-FUNC(632)
-FUNC(633)
-FUNC(634)
-FUNC(635)
-FUNC(636)
-FUNC(637)
-FUNC(638)
-FUNC(639)
-FUNC(640)
-FUNC(641)
-FUNC(642)
-FUNC(643)
-FUNC(644)
-FUNC(645)
-FUNC(646)
-FUNC(647)
-FUNC(648)
-FUNC(649)
-FUNC(650)
-FUNC(651)
-FUNC(652)
-FUNC(653)
-FUNC(654)
-FUNC(655)
-FUNC(656)
-FUNC(657)
-FUNC(658)
-FUNC(659)
-FUNC(660)
-FUNC(661)
-FUNC(662)
-FUNC(663)
-FUNC(664)
-FUNC(665)
-FUNC(666)
-FUNC(667)
-FUNC(668)
-FUNC(669)
-FUNC(670)
-FUNC(671)
-FUNC(672)
-FUNC(673)
-FUNC(674)
-FUNC(675)
-FUNC(676)
-FUNC(677)
-FUNC(678)
-FUNC(679)
-FUNC(680)
-FUNC(681)
-FUNC(682)
-FUNC(683)
-FUNC(684)
-FUNC(685)
-FUNC(686)
-FUNC(687)
-FUNC(688)
-FUNC(689)
-FUNC(690)
-FUNC(691)
-FUNC(692)
-FUNC(693)
-FUNC(694)
-FUNC(695)
-FUNC(696)
-FUNC(697)
-FUNC(698)
-FUNC(699)
-FUNC(700)
-FUNC(701)
-FUNC(702)
-FUNC(703)
-FUNC(704)
-FUNC(705)
-FUNC(706)
-FUNC(707)
-FUNC(708)
-FUNC(709)
-FUNC(710)
-FUNC(711)
-FUNC(712)
-FUNC(713)
-FUNC(714)
-FUNC(715)
-FUNC(716)
-FUNC(717)
-FUNC(718)
-FUNC(719)
-FUNC(720)
-FUNC(721)
-FUNC(722)
-FUNC(723)
-FUNC(724)
-FUNC(725)
-FUNC(726)
-FUNC(727)
-FUNC(728)
-FUNC(729)
-FUNC(730)
-FUNC(731)
-FUNC(732)
-FUNC(733)
-FUNC(734)
-FUNC(735)
-FUNC(736)
-FUNC(737)
-FUNC(738)
-FUNC(739)
-FUNC(740)
-FUNC(741)
-FUNC(742)
-FUNC(743)
-FUNC(744)
-FUNC(745)
-FUNC(746)
-FUNC(747)
-FUNC(748)
-FUNC(749)
-FUNC(750)
-FUNC(751)
-FUNC(752)
-FUNC(753)
-FUNC(754)
-FUNC(755)
-FUNC(756)
-FUNC(757)
-FUNC(758)
-FUNC(759)
-FUNC(760)
-FUNC(761)
-FUNC(762)
-FUNC(763)
-FUNC(764)
-FUNC(765)
-FUNC(766)
-FUNC(767)
-FUNC(768)
-FUNC(769)
-FUNC(770)
-FUNC(771)
-FUNC(772)
-FUNC(773)
-FUNC(774)
-FUNC(775)
-FUNC(776)
-FUNC(777)
-FUNC(778)
-FUNC(779)
-FUNC(780)
-FUNC(781)
-FUNC(782)
-FUNC(783)
-FUNC(784)
-FUNC(785)
-FUNC(786)
-FUNC(787)
-FUNC(788)
-FUNC(789)
-FUNC(790)
-FUNC(791)
-FUNC(792)
-FUNC(793)
-FUNC(794)
-FUNC(795)
-FUNC(796)
-FUNC(797)
-FUNC(798)
-FUNC(799)
-FUNC(800)
-FUNC(801)
-FUNC(802)
-FUNC(803)
-FUNC(804)
-FUNC(805)
-FUNC(806)
-FUNC(807)
-FUNC(808)
-FUNC(809)
-FUNC(810)
-FUNC(811)
-FUNC(812)
-FUNC(813)
-FUNC(814)
-FUNC(815)
-FUNC(816)
-FUNC(817)
-FUNC(818)
-FUNC(819)
-FUNC(820)
-FUNC(821)
-FUNC(822)
-FUNC(823)
-FUNC(824)
-FUNC(825)
-FUNC(826)
-FUNC(827)
-FUNC(828)
-FUNC(829)
-FUNC(830)
-FUNC(831)
-FUNC(832)
-FUNC(833)
-FUNC(834)
-FUNC(835)
-FUNC(836)
-FUNC(837)
-FUNC(838)
-FUNC(839)
-FUNC(840)
-FUNC(841)
-FUNC(842)
-FUNC(843)
-FUNC(844)
-FUNC(845)
-FUNC(846)
-FUNC(847)
-FUNC(848)
-FUNC(849)
-FUNC(850)
-FUNC(851)
-FUNC(852)
-FUNC(853)
-FUNC(854)
-FUNC(855)
-FUNC(856)
-FUNC(857)
-FUNC(858)
-FUNC(859)
-FUNC(860)
-FUNC(861)
-FUNC(862)
-FUNC(863)
-FUNC(864)
-FUNC(865)
-FUNC(866)
-FUNC(867)
-FUNC(868)
-FUNC(869)
-FUNC(870)
-FUNC(871)
-FUNC(872)
-FUNC(873)
-FUNC(874)
-FUNC(875)
-FUNC(876)
-FUNC(877)
-FUNC(878)
-FUNC(879)
-FUNC(880)
-FUNC(881)
-FUNC(882)
-FUNC(883)
-FUNC(884)
-FUNC(885)
-FUNC(886)
-FUNC(887)
-FUNC(888)
-FUNC(889)
-FUNC(890)
-FUNC(891)
-FUNC(892)
-FUNC(893)
-FUNC(894)
-FUNC(895)
-FUNC(896)
-FUNC(897)
-FUNC(898)
-FUNC(899)
-FUNC(900)
-FUNC(901)
-FUNC(902)
-FUNC(903)
-FUNC(904)
-FUNC(905)
-FUNC(906)
-FUNC(907)
-FUNC(908)
-FUNC(909)
-FUNC(910)
-FUNC(911)
-FUNC(912)
-FUNC(913)
-FUNC(914)
-FUNC(915)
-FUNC(916)
-FUNC(917)
-FUNC(918)
-FUNC(919)
-FUNC(920)
-FUNC(921)
-FUNC(922)
-FUNC(923)
-FUNC(924)
-FUNC(925)
-FUNC(926)
-FUNC(927)
-FUNC(928)
-FUNC(929)
-FUNC(930)
-FUNC(931)
-FUNC(932)
-FUNC(933)
-FUNC(934)
-FUNC(935)
-FUNC(936)
-FUNC(937)
-FUNC(938)
-FUNC(939)
-FUNC(940)
-FUNC(941)
-FUNC(942)
-FUNC(943)
-FUNC(944)
-FUNC(945)
-FUNC(946)
-FUNC(947)
-FUNC(948)
-FUNC(949)
-FUNC(950)
-FUNC(951)
-FUNC(952)
-FUNC(953)
-FUNC(954)
-FUNC(955)
-FUNC(956)
-FUNC(957)
-FUNC(958)
-FUNC(959)
-FUNC(960)
-FUNC(961)
-FUNC(962)
-FUNC(963)
-FUNC(964)
-FUNC(965)
-FUNC(966)
-FUNC(967)
-FUNC(968)
-FUNC(969)
-FUNC(970)
-FUNC(971)
-FUNC(972)
-FUNC(973)
-FUNC(974)
-FUNC(975)
-FUNC(976)
-FUNC(977)
-FUNC(978)
-FUNC(979)
-FUNC(980)
-FUNC(981)
-FUNC(982)
-FUNC(983)
-FUNC(984)
-FUNC(985)
-FUNC(986)
-FUNC(987)
-FUNC(988)
-FUNC(989)
-FUNC(990)
-FUNC(991)
-FUNC(992)
-FUNC(993)
-FUNC(994)
-FUNC(995)
-FUNC(996)
-FUNC(997)
-FUNC(998)
-FUNC(999)
-FUNC(1000)
-FUNC(1001)
-FUNC(1002)
-FUNC(1003)
-FUNC(1004)
-FUNC(1005)
-FUNC(1006)
-FUNC(1007)
-FUNC(1008)
-FUNC(1009)
-FUNC(1010)
-FUNC(1011)
-FUNC(1012)
-FUNC(1013)
-FUNC(1014)
-FUNC(1015)
-FUNC(1016)
-FUNC(1017)
-FUNC(1018)
-FUNC(1019)
-FUNC(1020)
-FUNC(1021)
-FUNC(1022)
-FUNC(1023)
-FUNC(1024)
-FUNC(1025)
-FUNC(1026)
-FUNC(1027)
-FUNC(1028)
-FUNC(1029)
-FUNC(1030)
-FUNC(1031)
-FUNC(1032)
-FUNC(1033)
-FUNC(1034)
-FUNC(1035)
-FUNC(1036)
-FUNC(1037)
-FUNC(1038)
-FUNC(1039)
-FUNC(1040)
-FUNC(1041)
-FUNC(1042)
-FUNC(1043)
-FUNC(1044)
-FUNC(1045)
-FUNC(1046)
-FUNC(1047)
-FUNC(1048)
-FUNC(1049)
-FUNC(1050)
-FUNC(1051)
-FUNC(1052)
-FUNC(1053)
-FUNC(1054)
-FUNC(1055)
-FUNC(1056)
-FUNC(1057)
-FUNC(1058)
-FUNC(1059)
-FUNC(1060)
-FUNC(1061)
-FUNC(1062)
-FUNC(1063)
-FUNC(1064)
-FUNC(1065)
-FUNC(1066)
-FUNC(1067)
-FUNC(1068)
-FUNC(1069)
-FUNC(1070)
-FUNC(1071)
-FUNC(1072)
-FUNC(1073)
-FUNC(1074)
-FUNC(1075)
-FUNC(1076)
-FUNC(1077)
-FUNC(1078)
-FUNC(1079)
-FUNC(1080)
-FUNC(1081)
-FUNC(1082)
-FUNC(1083)
-FUNC(1084)
-FUNC(1085)
-FUNC(1086)
-FUNC(1087)
-FUNC(1088)
-FUNC(1089)
-FUNC(1090)
-FUNC(1091)
-FUNC(1092)
-FUNC(1093)
-FUNC(1094)
-FUNC(1095)
-FUNC(1096)
-FUNC(1097)
-FUNC(1098)
-FUNC(1099)
-FUNC(1100)
-FUNC(1101)
-FUNC(1102)
-FUNC(1103)
-FUNC(1104)
-FUNC(1105)
-FUNC(1106)
-FUNC(1107)
-FUNC(1108)
-FUNC(1109)
-FUNC(1110)
-FUNC(1111)
-FUNC(1112)
-FUNC(1113)
-FUNC(1114)
-FUNC(1115)
-FUNC(1116)
-FUNC(1117)
-FUNC(1118)
-FUNC(1119)
-FUNC(1120)
-FUNC(1121)
-FUNC(1122)
-FUNC(1123)
-FUNC(1124)
-FUNC(1125)
-FUNC(1126)
-FUNC(1127)
-FUNC(1128)
-FUNC(1129)
-FUNC(1130)
-FUNC(1131)
-FUNC(1132)
-FUNC(1133)
-FUNC(1134)
-FUNC(1135)
-FUNC(1136)
-FUNC(1137)
-FUNC(1138)
-FUNC(1139)
-FUNC(1140)
-FUNC(1141)
-FUNC(1142)
-FUNC(1143)
-FUNC(1144)
-FUNC(1145)
-FUNC(1146)
-FUNC(1147)
-FUNC(1148)
-FUNC(1149)
-FUNC(1150)
-FUNC(1151)
-FUNC(1152)
-FUNC(1153)
-FUNC(1154)
-FUNC(1155)
-FUNC(1156)
-FUNC(1157)
-FUNC(1158)
-FUNC(1159)
-FUNC(1160)
-FUNC(1161)
-FUNC(1162)
-FUNC(1163)
-FUNC(1164)
-FUNC(1165)
-FUNC(1166)
-FUNC(1167)
-FUNC(1168)
-FUNC(1169)
-FUNC(1170)
-FUNC(1171)
-FUNC(1172)
-FUNC(1173)
-FUNC(1174)
-FUNC(1175)
-FUNC(1176)
-FUNC(1177)
-FUNC(1178)
-FUNC(1179)
-FUNC(1180)
-FUNC(1181)
-FUNC(1182)
-FUNC(1183)
-FUNC(1184)
-FUNC(1185)
-FUNC(1186)
-FUNC(1187)
-FUNC(1188)
-FUNC(1189)
-FUNC(1190)
-FUNC(1191)
-FUNC(1192)
-FUNC(1193)
-FUNC(1194)
-FUNC(1195)
-FUNC(1196)
-FUNC(1197)
-FUNC(1198)
-FUNC(1199)
-FUNC(1200)
-FUNC(1201)
-FUNC(1202)
-FUNC(1203)
-FUNC(1204)
-FUNC(1205)
-FUNC(1206)
-FUNC(1207)
-FUNC(1208)
-FUNC(1209)
-FUNC(1210)
-FUNC(1211)
-FUNC(1212)
-FUNC(1213)
-FUNC(1214)
-FUNC(1215)
-FUNC(1216)
-FUNC(1217)
-FUNC(1218)
-FUNC(1219)
-FUNC(1220)
-FUNC(1221)
-FUNC(1222)
-FUNC(1223)
-FUNC(1224)
-FUNC(1225)
-FUNC(1226)
-FUNC(1227)
-FUNC(1228)
-FUNC(1229)
-FUNC(1230)
-FUNC(1231)
-FUNC(1232)
-FUNC(1233)
-FUNC(1234)
-FUNC(1235)
-FUNC(1236)
-FUNC(1237)
-FUNC(1238)
-FUNC(1239)
-FUNC(1240)
-FUNC(1241)
-FUNC(1242)
-FUNC(1243)
-FUNC(1244)
-FUNC(1245)
-FUNC(1246)
-FUNC(1247)
-FUNC(1248)
-FUNC(1249)
-FUNC(1250)
-FUNC(1251)
-FUNC(1252)
-FUNC(1253)
-FUNC(1254)
-FUNC(1255)
-FUNC(1256)
-FUNC(1257)
-FUNC(1258)
-FUNC(1259)
-FUNC(1260)
-FUNC(1261)
-FUNC(1262)
-FUNC(1263)
-FUNC(1264)
-FUNC(1265)
-FUNC(1266)
-FUNC(1267)
-FUNC(1268)
-FUNC(1269)
-FUNC(1270)
-FUNC(1271)
-FUNC(1272)
-FUNC(1273)
-FUNC(1274)
-FUNC(1275)
-FUNC(1276)
-FUNC(1277)
-FUNC(1278)
-FUNC(1279)
-FUNC(1280)
-FUNC(1281)
-FUNC(1282)
-FUNC(1283)
-FUNC(1284)
-FUNC(1285)
-FUNC(1286)
-FUNC(1287)
-FUNC(1288)
-FUNC(1289)
-FUNC(1290)
-FUNC(1291)
-FUNC(1292)
-FUNC(1293)
-FUNC(1294)
-FUNC(1295)
-FUNC(1296)
-FUNC(1297)
-FUNC(1298)
-FUNC(1299)
-FUNC(1300)
-FUNC(1301)
-FUNC(1302)
-FUNC(1303)
-FUNC(1304)
-FUNC(1305)
-FUNC(1306)
-FUNC(1307)
-FUNC(1308)
-FUNC(1309)
-FUNC(1310)
-FUNC(1311)
-FUNC(1312)
-FUNC(1313)
-FUNC(1314)
-FUNC(1315)
-FUNC(1316)
-FUNC(1317)
-FUNC(1318)
-FUNC(1319)
-FUNC(1320)
-FUNC(1321)
-FUNC(1322)
-FUNC(1323)
-FUNC(1324)
-FUNC(1325)
-FUNC(1326)
-FUNC(1327)
-FUNC(1328)
-FUNC(1329)
-FUNC(1330)
-FUNC(1331)
-FUNC(1332)
-FUNC(1333)
-FUNC(1334)
-FUNC(1335)
-FUNC(1336)
-FUNC(1337)
-FUNC(1338)
-FUNC(1339)
-FUNC(1340)
-FUNC(1341)
-FUNC(1342)
-FUNC(1343)
-FUNC(1344)
-FUNC(1345)
-FUNC(1346)
-FUNC(1347)
-FUNC(1348)
-FUNC(1349)
-FUNC(1350)
-FUNC(1351)
-FUNC(1352)
-FUNC(1353)
-FUNC(1354)
-FUNC(1355)
-FUNC(1356)
-FUNC(1357)
-FUNC(1358)
-FUNC(1359)
-FUNC(1360)
-FUNC(1361)
-FUNC(1362)
-FUNC(1363)
-FUNC(1364)
-FUNC(1365)
-FUNC(1366)
-FUNC(1367)
-FUNC(1368)
-FUNC(1369)
-FUNC(1370)
-FUNC(1371)
-FUNC(1372)
-FUNC(1373)
-FUNC(1374)
-FUNC(1375)
-FUNC(1376)
-FUNC(1377)
-FUNC(1378)
-FUNC(1379)
-FUNC(1380)
-FUNC(1381)
-FUNC(1382)
-FUNC(1383)
-FUNC(1384)
-FUNC(1385)
-FUNC(1386)
-FUNC(1387)
-FUNC(1388)
-FUNC(1389)
-FUNC(1390)
-FUNC(1391)
-FUNC(1392)
-FUNC(1393)
-FUNC(1394)
-FUNC(1395)
-FUNC(1396)
-FUNC(1397)
-FUNC(1398)
-FUNC(1399)
-FUNC(1400)
-FUNC(1401)
-FUNC(1402)
-FUNC(1403)
-FUNC(1404)
-FUNC(1405)
-FUNC(1406)
-FUNC(1407)
-FUNC(1408)
-FUNC(1409)
-FUNC(1410)
-FUNC(1411)
-FUNC(1412)
-FUNC(1413)
-FUNC(1414)
-FUNC(1415)
-FUNC(1416)
-FUNC(1417)
-FUNC(1418)
-FUNC(1419)
-FUNC(1420)
-FUNC(1421)
-FUNC(1422)
-FUNC(1423)
-FUNC(1424)
-FUNC(1425)
-FUNC(1426)
-FUNC(1427)
-FUNC(1428)
-FUNC(1429)
-FUNC(1430)
-FUNC(1431)
-FUNC(1432)
-FUNC(1433)
-FUNC(1434)
-FUNC(1435)
-FUNC(1436)
-FUNC(1437)
-FUNC(1438)
-FUNC(1439)
-FUNC(1440)
-FUNC(1441)
-FUNC(1442)
-FUNC(1443)
-FUNC(1444)
-FUNC(1445)
-FUNC(1446)
-FUNC(1447)
-FUNC(1448)
-FUNC(1449)
-FUNC(1450)
-FUNC(1451)
-FUNC(1452)
-FUNC(1453)
-FUNC(1454)
-FUNC(1455)
-FUNC(1456)
-FUNC(1457)
-FUNC(1458)
-FUNC(1459)
-FUNC(1460)
-FUNC(1461)
-FUNC(1462)
-FUNC(1463)
-FUNC(1464)
-FUNC(1465)
-FUNC(1466)
-FUNC(1467)
-FUNC(1468)
-FUNC(1469)
-FUNC(1470)
-FUNC(1471)
-FUNC(1472)
-FUNC(1473)
-FUNC(1474)
-FUNC(1475)
-FUNC(1476)
-FUNC(1477)
-FUNC(1478)
-FUNC(1479)
-FUNC(1480)
-FUNC(1481)
-FUNC(1482)
-FUNC(1483)
-FUNC(1484)
-FUNC(1485)
-FUNC(1486)
-FUNC(1487)
-FUNC(1488)
-FUNC(1489)
-FUNC(1490)
-FUNC(1491)
-FUNC(1492)
-FUNC(1493)
-FUNC(1494)
-FUNC(1495)
-FUNC(1496)
-FUNC(1497)
-FUNC(1498)
-FUNC(1499)
-FUNC(1500)
-FUNC(1501)
-FUNC(1502)
-FUNC(1503)
-FUNC(1504)
-FUNC(1505)
-FUNC(1506)
-FUNC(1507)
-FUNC(1508)
-FUNC(1509)
-FUNC(1510)
-FUNC(1511)
-FUNC(1512)
-FUNC(1513)
-FUNC(1514)
-FUNC(1515)
-FUNC(1516)
-FUNC(1517)
-FUNC(1518)
-FUNC(1519)
-FUNC(1520)
-FUNC(1521)
-FUNC(1522)
-FUNC(1523)
-FUNC(1524)
-FUNC(1525)
-FUNC(1526)
-FUNC(1527)
-FUNC(1528)
-FUNC(1529)
-FUNC(1530)
-FUNC(1531)
-FUNC(1532)
-FUNC(1533)
-FUNC(1534)
-FUNC(1535)
-FUNC(1536)
-FUNC(1537)
-FUNC(1538)
-FUNC(1539)
-FUNC(1540)
-FUNC(1541)
-FUNC(1542)
-FUNC(1543)
-FUNC(1544)
-FUNC(1545)
-FUNC(1546)
-FUNC(1547)
-FUNC(1548)
-FUNC(1549)
-FUNC(1550)
-FUNC(1551)
-FUNC(1552)
-FUNC(1553)
-FUNC(1554)
-FUNC(1555)
-FUNC(1556)
-FUNC(1557)
-FUNC(1558)
-FUNC(1559)
-FUNC(1560)
-FUNC(1561)
-FUNC(1562)
-FUNC(1563)
-FUNC(1564)
-FUNC(1565)
-FUNC(1566)
-FUNC(1567)
-FUNC(1568)
-FUNC(1569)
-FUNC(1570)
-FUNC(1571)
-FUNC(1572)
-FUNC(1573)
-FUNC(1574)
-FUNC(1575)
-FUNC(1576)
-FUNC(1577)
-FUNC(1578)
-FUNC(1579)
-FUNC(1580)
-FUNC(1581)
-FUNC(1582)
-FUNC(1583)
-FUNC(1584)
-FUNC(1585)
-FUNC(1586)
-FUNC(1587)
-FUNC(1588)
-FUNC(1589)
-FUNC(1590)
-FUNC(1591)
-FUNC(1592)
-FUNC(1593)
-FUNC(1594)
-FUNC(1595)
-FUNC(1596)
-FUNC(1597)
-FUNC(1598)
-FUNC(1599)
-FUNC(1600)
-FUNC(1601)
-FUNC(1602)
-FUNC(1603)
-FUNC(1604)
-FUNC(1605)
-FUNC(1606)
-FUNC(1607)
-FUNC(1608)
-FUNC(1609)
-FUNC(1610)
-FUNC(1611)
-FUNC(1612)
-FUNC(1613)
-FUNC(1614)
-FUNC(1615)
-FUNC(1616)
-FUNC(1617)
-FUNC(1618)
-FUNC(1619)
-FUNC(1620)
-FUNC(1621)
-FUNC(1622)
-FUNC(1623)
-FUNC(1624)
-FUNC(1625)
-FUNC(1626)
-FUNC(1627)
-FUNC(1628)
-FUNC(1629)
-FUNC(1630)
-FUNC(1631)
-FUNC(1632)
-FUNC(1633)
-FUNC(1634)
-FUNC(1635)
-FUNC(1636)
-FUNC(1637)
-FUNC(1638)
-FUNC(1639)
-FUNC(1640)
-FUNC(1641)
-FUNC(1642)
-FUNC(1643)
-FUNC(1644)
-FUNC(1645)
-FUNC(1646)
-FUNC(1647)
-FUNC(1648)
-FUNC(1649)
-FUNC(1650)
-FUNC(1651)
-FUNC(1652)
-FUNC(1653)
-FUNC(1654)
-FUNC(1655)
-FUNC(1656)
-FUNC(1657)
-FUNC(1658)
-FUNC(1659)
-FUNC(1660)
-FUNC(1661)
-FUNC(1662)
-FUNC(1663)
-FUNC(1664)
-FUNC(1665)
-FUNC(1666)
-FUNC(1667)
-FUNC(1668)
-FUNC(1669)
-FUNC(1670)
-FUNC(1671)
-FUNC(1672)
-FUNC(1673)
-FUNC(1674)
-FUNC(1675)
-FUNC(1676)
-FUNC(1677)
-FUNC(1678)
-FUNC(1679)
-FUNC(1680)
-FUNC(1681)
-FUNC(1682)
-FUNC(1683)
-FUNC(1684)
-FUNC(1685)
-FUNC(1686)
-FUNC(1687)
-FUNC(1688)
-FUNC(1689)
-FUNC(1690)
-FUNC(1691)
-FUNC(1692)
-FUNC(1693)
-FUNC(1694)
-FUNC(1695)
-FUNC(1696)
-FUNC(1697)
-FUNC(1698)
-FUNC(1699)
-FUNC(1700)
-FUNC(1701)
-FUNC(1702)
-FUNC(1703)
-FUNC(1704)
-FUNC(1705)
-FUNC(1706)
-FUNC(1707)
-FUNC(1708)
-FUNC(1709)
-FUNC(1710)
-FUNC(1711)
-FUNC(1712)
-FUNC(1713)
-FUNC(1714)
-FUNC(1715)
-FUNC(1716)
-FUNC(1717)
-FUNC(1718)
-FUNC(1719)
-FUNC(1720)
-FUNC(1721)
-FUNC(1722)
-FUNC(1723)
-FUNC(1724)
-FUNC(1725)
-FUNC(1726)
-FUNC(1727)
-FUNC(1728)
-FUNC(1729)
-FUNC(1730)
-FUNC(1731)
-FUNC(1732)
-FUNC(1733)
-FUNC(1734)
-FUNC(1735)
-FUNC(1736)
-FUNC(1737)
-FUNC(1738)
-FUNC(1739)
-FUNC(1740)
-FUNC(1741)
-FUNC(1742)
-FUNC(1743)
-FUNC(1744)
-FUNC(1745)
-FUNC(1746)
-FUNC(1747)
-FUNC(1748)
-FUNC(1749)
-FUNC(1750)
-FUNC(1751)
-FUNC(1752)
-FUNC(1753)
-FUNC(1754)
-FUNC(1755)
-FUNC(1756)
-FUNC(1757)
-FUNC(1758)
-FUNC(1759)
-FUNC(1760)
-FUNC(1761)
-FUNC(1762)
-FUNC(1763)
-FUNC(1764)
-FUNC(1765)
-FUNC(1766)
-FUNC(1767)
-FUNC(1768)
-FUNC(1769)
-FUNC(1770)
-FUNC(1771)
-FUNC(1772)
-FUNC(1773)
-FUNC(1774)
-FUNC(1775)
-FUNC(1776)
-FUNC(1777)
-FUNC(1778)
-FUNC(1779)
-FUNC(1780)
-FUNC(1781)
-FUNC(1782)
-FUNC(1783)
-FUNC(1784)
-FUNC(1785)
-FUNC(1786)
-FUNC(1787)
-FUNC(1788)
-FUNC(1789)
-FUNC(1790)
-FUNC(1791)
-FUNC(1792)
-FUNC(1793)
-FUNC(1794)
-FUNC(1795)
-FUNC(1796)
-FUNC(1797)
-FUNC(1798)
-FUNC(1799)
-FUNC(1800)
-FUNC(1801)
-FUNC(1802)
-FUNC(1803)
-FUNC(1804)
-FUNC(1805)
-FUNC(1806)
-FUNC(1807)
-FUNC(1808)
-FUNC(1809)
-FUNC(1810)
-FUNC(1811)
-FUNC(1812)
-FUNC(1813)
-FUNC(1814)
-FUNC(1815)
-FUNC(1816)
-FUNC(1817)
-FUNC(1818)
-FUNC(1819)
-FUNC(1820)
-FUNC(1821)
-FUNC(1822)
-FUNC(1823)
-FUNC(1824)
-FUNC(1825)
-FUNC(1826)
-FUNC(1827)
-FUNC(1828)
-FUNC(1829)
-FUNC(1830)
-FUNC(1831)
-FUNC(1832)
-FUNC(1833)
-FUNC(1834)
-FUNC(1835)
-FUNC(1836)
-FUNC(1837)
-FUNC(1838)
-FUNC(1839)
-FUNC(1840)
-FUNC(1841)
-FUNC(1842)
-FUNC(1843)
-FUNC(1844)
-FUNC(1845)
-FUNC(1846)
-FUNC(1847)
-FUNC(1848)
-FUNC(1849)
-FUNC(1850)
-FUNC(1851)
-FUNC(1852)
-FUNC(1853)
-FUNC(1854)
-FUNC(1855)
-FUNC(1856)
-FUNC(1857)
-FUNC(1858)
-FUNC(1859)
-FUNC(1860)
-FUNC(1861)
-FUNC(1862)
-FUNC(1863)
-FUNC(1864)
-FUNC(1865)
-FUNC(1866)
-FUNC(1867)
-FUNC(1868)
-FUNC(1869)
-FUNC(1870)
-FUNC(1871)
-FUNC(1872)
-FUNC(1873)
-FUNC(1874)
-FUNC(1875)
-FUNC(1876)
-FUNC(1877)
-FUNC(1878)
-FUNC(1879)
-FUNC(1880)
-FUNC(1881)
-FUNC(1882)
-FUNC(1883)
-FUNC(1884)
-FUNC(1885)
-FUNC(1886)
-FUNC(1887)
-FUNC(1888)
-FUNC(1889)
-FUNC(1890)
-FUNC(1891)
-FUNC(1892)
-FUNC(1893)
-FUNC(1894)
-FUNC(1895)
-FUNC(1896)
-FUNC(1897)
-FUNC(1898)
-FUNC(1899)
-FUNC(1900)
-FUNC(1901)
-FUNC(1902)
-FUNC(1903)
-FUNC(1904)
-FUNC(1905)
-FUNC(1906)
-FUNC(1907)
-FUNC(1908)
-FUNC(1909)
-FUNC(1910)
-FUNC(1911)
-FUNC(1912)
-FUNC(1913)
-FUNC(1914)
-FUNC(1915)
-FUNC(1916)
-FUNC(1917)
-FUNC(1918)
-FUNC(1919)
-FUNC(1920)
-FUNC(1921)
-FUNC(1922)
-FUNC(1923)
-FUNC(1924)
-FUNC(1925)
-FUNC(1926)
-FUNC(1927)
-FUNC(1928)
-FUNC(1929)
-FUNC(1930)
-FUNC(1931)
-FUNC(1932)
-FUNC(1933)
-FUNC(1934)
-FUNC(1935)
-FUNC(1936)
-FUNC(1937)
-FUNC(1938)
-FUNC(1939)
-FUNC(1940)
-FUNC(1941)
-FUNC(1942)
-FUNC(1943)
-FUNC(1944)
-FUNC(1945)
-FUNC(1946)
-FUNC(1947)
-FUNC(1948)
-FUNC(1949)
-FUNC(1950)
-FUNC(1951)
-FUNC(1952)
-FUNC(1953)
-FUNC(1954)
-FUNC(1955)
-FUNC(1956)
-FUNC(1957)
-FUNC(1958)
-FUNC(1959)
-FUNC(1960)
-FUNC(1961)
-FUNC(1962)
-FUNC(1963)
-FUNC(1964)
-FUNC(1965)
-FUNC(1966)
-FUNC(1967)
-FUNC(1968)
-FUNC(1969)
-FUNC(1970)
-FUNC(1971)
-FUNC(1972)
-FUNC(1973)
-FUNC(1974)
-FUNC(1975)
-FUNC(1976)
-FUNC(1977)
-FUNC(1978)
-FUNC(1979)
-FUNC(1980)
-FUNC(1981)
-FUNC(1982)
-FUNC(1983)
-FUNC(1984)
-FUNC(1985)
-FUNC(1986)
-FUNC(1987)
-FUNC(1988)
-FUNC(1989)
-FUNC(1990)
-FUNC(1991)
-FUNC(1992)
-FUNC(1993)
-FUNC(1994)
-FUNC(1995)
-FUNC(1996)
-FUNC(1997)
-FUNC(1998)
-FUNC(1999)
-FUNC(2000)
+/*
+* 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: 
+*
+*/
+/* 
+This is jsut some "compiler fibre" for the compiler to chew
+on as part of a compilation performace test
+*/
+
+#define FUNC(VARIABLE)	\
+int function_##VARIABLE(void)	\
+{	\
+	int x,y,z;	\
+	x=VARIABLE+30* 10-1;	\
+	y=x*4;	\
+	\
+	\
+	x=y+1;	\
+	\
+	int a[VARIABLE];	\
+	\
+	\
+	\
+	for (z=0; z < 1000+VARIABLE; z++)	\
+	{	\
+		x+=a[z];		\
+	}	\
+	\
+	return x;	\
+}
+
+
+
+FUNC(1)
+FUNC(2)
+FUNC(3)
+FUNC(4)
+FUNC(5)
+FUNC(6)
+FUNC(7)
+FUNC(8)
+FUNC(9)
+FUNC(10)
+FUNC(11)
+FUNC(12)
+FUNC(13)
+FUNC(14)
+FUNC(15)
+FUNC(16)
+FUNC(17)
+FUNC(18)
+FUNC(19)
+FUNC(20)
+FUNC(21)
+FUNC(22)
+FUNC(23)
+FUNC(24)
+FUNC(25)
+FUNC(26)
+FUNC(27)
+FUNC(28)
+FUNC(29)
+FUNC(30)
+FUNC(31)
+FUNC(32)
+FUNC(33)
+FUNC(34)
+FUNC(35)
+FUNC(36)
+FUNC(37)
+FUNC(38)
+FUNC(39)
+FUNC(40)
+FUNC(41)
+FUNC(42)
+FUNC(43)
+FUNC(44)
+FUNC(45)
+FUNC(46)
+FUNC(47)
+FUNC(48)
+FUNC(49)
+FUNC(50)
+FUNC(51)
+FUNC(52)
+FUNC(53)
+FUNC(54)
+FUNC(55)
+FUNC(56)
+FUNC(57)
+FUNC(58)
+FUNC(59)
+FUNC(60)
+FUNC(61)
+FUNC(62)
+FUNC(63)
+FUNC(64)
+FUNC(65)
+FUNC(66)
+FUNC(67)
+FUNC(68)
+FUNC(69)
+FUNC(70)
+FUNC(71)
+FUNC(72)
+FUNC(73)
+FUNC(74)
+FUNC(75)
+FUNC(76)
+FUNC(77)
+FUNC(78)
+FUNC(79)
+FUNC(80)
+FUNC(81)
+FUNC(82)
+FUNC(83)
+FUNC(84)
+FUNC(85)
+FUNC(86)
+FUNC(87)
+FUNC(88)
+FUNC(89)
+FUNC(90)
+FUNC(91)
+FUNC(92)
+FUNC(93)
+FUNC(94)
+FUNC(95)
+FUNC(96)
+FUNC(97)
+FUNC(98)
+FUNC(99)
+FUNC(100)
+FUNC(101)
+FUNC(102)
+FUNC(103)
+FUNC(104)
+FUNC(105)
+FUNC(106)
+FUNC(107)
+FUNC(108)
+FUNC(109)
+FUNC(110)
+FUNC(111)
+FUNC(112)
+FUNC(113)
+FUNC(114)
+FUNC(115)
+FUNC(116)
+FUNC(117)
+FUNC(118)
+FUNC(119)
+FUNC(120)
+FUNC(121)
+FUNC(122)
+FUNC(123)
+FUNC(124)
+FUNC(125)
+FUNC(126)
+FUNC(127)
+FUNC(128)
+FUNC(129)
+FUNC(130)
+FUNC(131)
+FUNC(132)
+FUNC(133)
+FUNC(134)
+FUNC(135)
+FUNC(136)
+FUNC(137)
+FUNC(138)
+FUNC(139)
+FUNC(140)
+FUNC(141)
+FUNC(142)
+FUNC(143)
+FUNC(144)
+FUNC(145)
+FUNC(146)
+FUNC(147)
+FUNC(148)
+FUNC(149)
+FUNC(150)
+FUNC(151)
+FUNC(152)
+FUNC(153)
+FUNC(154)
+FUNC(155)
+FUNC(156)
+FUNC(157)
+FUNC(158)
+FUNC(159)
+FUNC(160)
+FUNC(161)
+FUNC(162)
+FUNC(163)
+FUNC(164)
+FUNC(165)
+FUNC(166)
+FUNC(167)
+FUNC(168)
+FUNC(169)
+FUNC(170)
+FUNC(171)
+FUNC(172)
+FUNC(173)
+FUNC(174)
+FUNC(175)
+FUNC(176)
+FUNC(177)
+FUNC(178)
+FUNC(179)
+FUNC(180)
+FUNC(181)
+FUNC(182)
+FUNC(183)
+FUNC(184)
+FUNC(185)
+FUNC(186)
+FUNC(187)
+FUNC(188)
+FUNC(189)
+FUNC(190)
+FUNC(191)
+FUNC(192)
+FUNC(193)
+FUNC(194)
+FUNC(195)
+FUNC(196)
+FUNC(197)
+FUNC(198)
+FUNC(199)
+FUNC(200)
+FUNC(201)
+FUNC(202)
+FUNC(203)
+FUNC(204)
+FUNC(205)
+FUNC(206)
+FUNC(207)
+FUNC(208)
+FUNC(209)
+FUNC(210)
+FUNC(211)
+FUNC(212)
+FUNC(213)
+FUNC(214)
+FUNC(215)
+FUNC(216)
+FUNC(217)
+FUNC(218)
+FUNC(219)
+FUNC(220)
+FUNC(221)
+FUNC(222)
+FUNC(223)
+FUNC(224)
+FUNC(225)
+FUNC(226)
+FUNC(227)
+FUNC(228)
+FUNC(229)
+FUNC(230)
+FUNC(231)
+FUNC(232)
+FUNC(233)
+FUNC(234)
+FUNC(235)
+FUNC(236)
+FUNC(237)
+FUNC(238)
+FUNC(239)
+FUNC(240)
+FUNC(241)
+FUNC(242)
+FUNC(243)
+FUNC(244)
+FUNC(245)
+FUNC(246)
+FUNC(247)
+FUNC(248)
+FUNC(249)
+FUNC(250)
+FUNC(251)
+FUNC(252)
+FUNC(253)
+FUNC(254)
+FUNC(255)
+FUNC(256)
+FUNC(257)
+FUNC(258)
+FUNC(259)
+FUNC(260)
+FUNC(261)
+FUNC(262)
+FUNC(263)
+FUNC(264)
+FUNC(265)
+FUNC(266)
+FUNC(267)
+FUNC(268)
+FUNC(269)
+FUNC(270)
+FUNC(271)
+FUNC(272)
+FUNC(273)
+FUNC(274)
+FUNC(275)
+FUNC(276)
+FUNC(277)
+FUNC(278)
+FUNC(279)
+FUNC(280)
+FUNC(281)
+FUNC(282)
+FUNC(283)
+FUNC(284)
+FUNC(285)
+FUNC(286)
+FUNC(287)
+FUNC(288)
+FUNC(289)
+FUNC(290)
+FUNC(291)
+FUNC(292)
+FUNC(293)
+FUNC(294)
+FUNC(295)
+FUNC(296)
+FUNC(297)
+FUNC(298)
+FUNC(299)
+FUNC(300)
+FUNC(301)
+FUNC(302)
+FUNC(303)
+FUNC(304)
+FUNC(305)
+FUNC(306)
+FUNC(307)
+FUNC(308)
+FUNC(309)
+FUNC(310)
+FUNC(311)
+FUNC(312)
+FUNC(313)
+FUNC(314)
+FUNC(315)
+FUNC(316)
+FUNC(317)
+FUNC(318)
+FUNC(319)
+FUNC(320)
+FUNC(321)
+FUNC(322)
+FUNC(323)
+FUNC(324)
+FUNC(325)
+FUNC(326)
+FUNC(327)
+FUNC(328)
+FUNC(329)
+FUNC(330)
+FUNC(331)
+FUNC(332)
+FUNC(333)
+FUNC(334)
+FUNC(335)
+FUNC(336)
+FUNC(337)
+FUNC(338)
+FUNC(339)
+FUNC(340)
+FUNC(341)
+FUNC(342)
+FUNC(343)
+FUNC(344)
+FUNC(345)
+FUNC(346)
+FUNC(347)
+FUNC(348)
+FUNC(349)
+FUNC(350)
+FUNC(351)
+FUNC(352)
+FUNC(353)
+FUNC(354)
+FUNC(355)
+FUNC(356)
+FUNC(357)
+FUNC(358)
+FUNC(359)
+FUNC(360)
+FUNC(361)
+FUNC(362)
+FUNC(363)
+FUNC(364)
+FUNC(365)
+FUNC(366)
+FUNC(367)
+FUNC(368)
+FUNC(369)
+FUNC(370)
+FUNC(371)
+FUNC(372)
+FUNC(373)
+FUNC(374)
+FUNC(375)
+FUNC(376)
+FUNC(377)
+FUNC(378)
+FUNC(379)
+FUNC(380)
+FUNC(381)
+FUNC(382)
+FUNC(383)
+FUNC(384)
+FUNC(385)
+FUNC(386)
+FUNC(387)
+FUNC(388)
+FUNC(389)
+FUNC(390)
+FUNC(391)
+FUNC(392)
+FUNC(393)
+FUNC(394)
+FUNC(395)
+FUNC(396)
+FUNC(397)
+FUNC(398)
+FUNC(399)
+FUNC(400)
+FUNC(401)
+FUNC(402)
+FUNC(403)
+FUNC(404)
+FUNC(405)
+FUNC(406)
+FUNC(407)
+FUNC(408)
+FUNC(409)
+FUNC(410)
+FUNC(411)
+FUNC(412)
+FUNC(413)
+FUNC(414)
+FUNC(415)
+FUNC(416)
+FUNC(417)
+FUNC(418)
+FUNC(419)
+FUNC(420)
+FUNC(421)
+FUNC(422)
+FUNC(423)
+FUNC(424)
+FUNC(425)
+FUNC(426)
+FUNC(427)
+FUNC(428)
+FUNC(429)
+FUNC(430)
+FUNC(431)
+FUNC(432)
+FUNC(433)
+FUNC(434)
+FUNC(435)
+FUNC(436)
+FUNC(437)
+FUNC(438)
+FUNC(439)
+FUNC(440)
+FUNC(441)
+FUNC(442)
+FUNC(443)
+FUNC(444)
+FUNC(445)
+FUNC(446)
+FUNC(447)
+FUNC(448)
+FUNC(449)
+FUNC(450)
+FUNC(451)
+FUNC(452)
+FUNC(453)
+FUNC(454)
+FUNC(455)
+FUNC(456)
+FUNC(457)
+FUNC(458)
+FUNC(459)
+FUNC(460)
+FUNC(461)
+FUNC(462)
+FUNC(463)
+FUNC(464)
+FUNC(465)
+FUNC(466)
+FUNC(467)
+FUNC(468)
+FUNC(469)
+FUNC(470)
+FUNC(471)
+FUNC(472)
+FUNC(473)
+FUNC(474)
+FUNC(475)
+FUNC(476)
+FUNC(477)
+FUNC(478)
+FUNC(479)
+FUNC(480)
+FUNC(481)
+FUNC(482)
+FUNC(483)
+FUNC(484)
+FUNC(485)
+FUNC(486)
+FUNC(487)
+FUNC(488)
+FUNC(489)
+FUNC(490)
+FUNC(491)
+FUNC(492)
+FUNC(493)
+FUNC(494)
+FUNC(495)
+FUNC(496)
+FUNC(497)
+FUNC(498)
+FUNC(499)
+FUNC(500)
+FUNC(501)
+FUNC(502)
+FUNC(503)
+FUNC(504)
+FUNC(505)
+FUNC(506)
+FUNC(507)
+FUNC(508)
+FUNC(509)
+FUNC(510)
+FUNC(511)
+FUNC(512)
+FUNC(513)
+FUNC(514)
+FUNC(515)
+FUNC(516)
+FUNC(517)
+FUNC(518)
+FUNC(519)
+FUNC(520)
+FUNC(521)
+FUNC(522)
+FUNC(523)
+FUNC(524)
+FUNC(525)
+FUNC(526)
+FUNC(527)
+FUNC(528)
+FUNC(529)
+FUNC(530)
+FUNC(531)
+FUNC(532)
+FUNC(533)
+FUNC(534)
+FUNC(535)
+FUNC(536)
+FUNC(537)
+FUNC(538)
+FUNC(539)
+FUNC(540)
+FUNC(541)
+FUNC(542)
+FUNC(543)
+FUNC(544)
+FUNC(545)
+FUNC(546)
+FUNC(547)
+FUNC(548)
+FUNC(549)
+FUNC(550)
+FUNC(551)
+FUNC(552)
+FUNC(553)
+FUNC(554)
+FUNC(555)
+FUNC(556)
+FUNC(557)
+FUNC(558)
+FUNC(559)
+FUNC(560)
+FUNC(561)
+FUNC(562)
+FUNC(563)
+FUNC(564)
+FUNC(565)
+FUNC(566)
+FUNC(567)
+FUNC(568)
+FUNC(569)
+FUNC(570)
+FUNC(571)
+FUNC(572)
+FUNC(573)
+FUNC(574)
+FUNC(575)
+FUNC(576)
+FUNC(577)
+FUNC(578)
+FUNC(579)
+FUNC(580)
+FUNC(581)
+FUNC(582)
+FUNC(583)
+FUNC(584)
+FUNC(585)
+FUNC(586)
+FUNC(587)
+FUNC(588)
+FUNC(589)
+FUNC(590)
+FUNC(591)
+FUNC(592)
+FUNC(593)
+FUNC(594)
+FUNC(595)
+FUNC(596)
+FUNC(597)
+FUNC(598)
+FUNC(599)
+FUNC(600)
+FUNC(601)
+FUNC(602)
+FUNC(603)
+FUNC(604)
+FUNC(605)
+FUNC(606)
+FUNC(607)
+FUNC(608)
+FUNC(609)
+FUNC(610)
+FUNC(611)
+FUNC(612)
+FUNC(613)
+FUNC(614)
+FUNC(615)
+FUNC(616)
+FUNC(617)
+FUNC(618)
+FUNC(619)
+FUNC(620)
+FUNC(621)
+FUNC(622)
+FUNC(623)
+FUNC(624)
+FUNC(625)
+FUNC(626)
+FUNC(627)
+FUNC(628)
+FUNC(629)
+FUNC(630)
+FUNC(631)
+FUNC(632)
+FUNC(633)
+FUNC(634)
+FUNC(635)
+FUNC(636)
+FUNC(637)
+FUNC(638)
+FUNC(639)
+FUNC(640)
+FUNC(641)
+FUNC(642)
+FUNC(643)
+FUNC(644)
+FUNC(645)
+FUNC(646)
+FUNC(647)
+FUNC(648)
+FUNC(649)
+FUNC(650)
+FUNC(651)
+FUNC(652)
+FUNC(653)
+FUNC(654)
+FUNC(655)
+FUNC(656)
+FUNC(657)
+FUNC(658)
+FUNC(659)
+FUNC(660)
+FUNC(661)
+FUNC(662)
+FUNC(663)
+FUNC(664)
+FUNC(665)
+FUNC(666)
+FUNC(667)
+FUNC(668)
+FUNC(669)
+FUNC(670)
+FUNC(671)
+FUNC(672)
+FUNC(673)
+FUNC(674)
+FUNC(675)
+FUNC(676)
+FUNC(677)
+FUNC(678)
+FUNC(679)
+FUNC(680)
+FUNC(681)
+FUNC(682)
+FUNC(683)
+FUNC(684)
+FUNC(685)
+FUNC(686)
+FUNC(687)
+FUNC(688)
+FUNC(689)
+FUNC(690)
+FUNC(691)
+FUNC(692)
+FUNC(693)
+FUNC(694)
+FUNC(695)
+FUNC(696)
+FUNC(697)
+FUNC(698)
+FUNC(699)
+FUNC(700)
+FUNC(701)
+FUNC(702)
+FUNC(703)
+FUNC(704)
+FUNC(705)
+FUNC(706)
+FUNC(707)
+FUNC(708)
+FUNC(709)
+FUNC(710)
+FUNC(711)
+FUNC(712)
+FUNC(713)
+FUNC(714)
+FUNC(715)
+FUNC(716)
+FUNC(717)
+FUNC(718)
+FUNC(719)
+FUNC(720)
+FUNC(721)
+FUNC(722)
+FUNC(723)
+FUNC(724)
+FUNC(725)
+FUNC(726)
+FUNC(727)
+FUNC(728)
+FUNC(729)
+FUNC(730)
+FUNC(731)
+FUNC(732)
+FUNC(733)
+FUNC(734)
+FUNC(735)
+FUNC(736)
+FUNC(737)
+FUNC(738)
+FUNC(739)
+FUNC(740)
+FUNC(741)
+FUNC(742)
+FUNC(743)
+FUNC(744)
+FUNC(745)
+FUNC(746)
+FUNC(747)
+FUNC(748)
+FUNC(749)
+FUNC(750)
+FUNC(751)
+FUNC(752)
+FUNC(753)
+FUNC(754)
+FUNC(755)
+FUNC(756)
+FUNC(757)
+FUNC(758)
+FUNC(759)
+FUNC(760)
+FUNC(761)
+FUNC(762)
+FUNC(763)
+FUNC(764)
+FUNC(765)
+FUNC(766)
+FUNC(767)
+FUNC(768)
+FUNC(769)
+FUNC(770)
+FUNC(771)
+FUNC(772)
+FUNC(773)
+FUNC(774)
+FUNC(775)
+FUNC(776)
+FUNC(777)
+FUNC(778)
+FUNC(779)
+FUNC(780)
+FUNC(781)
+FUNC(782)
+FUNC(783)
+FUNC(784)
+FUNC(785)
+FUNC(786)
+FUNC(787)
+FUNC(788)
+FUNC(789)
+FUNC(790)
+FUNC(791)
+FUNC(792)
+FUNC(793)
+FUNC(794)
+FUNC(795)
+FUNC(796)
+FUNC(797)
+FUNC(798)
+FUNC(799)
+FUNC(800)
+FUNC(801)
+FUNC(802)
+FUNC(803)
+FUNC(804)
+FUNC(805)
+FUNC(806)
+FUNC(807)
+FUNC(808)
+FUNC(809)
+FUNC(810)
+FUNC(811)
+FUNC(812)
+FUNC(813)
+FUNC(814)
+FUNC(815)
+FUNC(816)
+FUNC(817)
+FUNC(818)
+FUNC(819)
+FUNC(820)
+FUNC(821)
+FUNC(822)
+FUNC(823)
+FUNC(824)
+FUNC(825)
+FUNC(826)
+FUNC(827)
+FUNC(828)
+FUNC(829)
+FUNC(830)
+FUNC(831)
+FUNC(832)
+FUNC(833)
+FUNC(834)
+FUNC(835)
+FUNC(836)
+FUNC(837)
+FUNC(838)
+FUNC(839)
+FUNC(840)
+FUNC(841)
+FUNC(842)
+FUNC(843)
+FUNC(844)
+FUNC(845)
+FUNC(846)
+FUNC(847)
+FUNC(848)
+FUNC(849)
+FUNC(850)
+FUNC(851)
+FUNC(852)
+FUNC(853)
+FUNC(854)
+FUNC(855)
+FUNC(856)
+FUNC(857)
+FUNC(858)
+FUNC(859)
+FUNC(860)
+FUNC(861)
+FUNC(862)
+FUNC(863)
+FUNC(864)
+FUNC(865)
+FUNC(866)
+FUNC(867)
+FUNC(868)
+FUNC(869)
+FUNC(870)
+FUNC(871)
+FUNC(872)
+FUNC(873)
+FUNC(874)
+FUNC(875)
+FUNC(876)
+FUNC(877)
+FUNC(878)
+FUNC(879)
+FUNC(880)
+FUNC(881)
+FUNC(882)
+FUNC(883)
+FUNC(884)
+FUNC(885)
+FUNC(886)
+FUNC(887)
+FUNC(888)
+FUNC(889)
+FUNC(890)
+FUNC(891)
+FUNC(892)
+FUNC(893)
+FUNC(894)
+FUNC(895)
+FUNC(896)
+FUNC(897)
+FUNC(898)
+FUNC(899)
+FUNC(900)
+FUNC(901)
+FUNC(902)
+FUNC(903)
+FUNC(904)
+FUNC(905)
+FUNC(906)
+FUNC(907)
+FUNC(908)
+FUNC(909)
+FUNC(910)
+FUNC(911)
+FUNC(912)
+FUNC(913)
+FUNC(914)
+FUNC(915)
+FUNC(916)
+FUNC(917)
+FUNC(918)
+FUNC(919)
+FUNC(920)
+FUNC(921)
+FUNC(922)
+FUNC(923)
+FUNC(924)
+FUNC(925)
+FUNC(926)
+FUNC(927)
+FUNC(928)
+FUNC(929)
+FUNC(930)
+FUNC(931)
+FUNC(932)
+FUNC(933)
+FUNC(934)
+FUNC(935)
+FUNC(936)
+FUNC(937)
+FUNC(938)
+FUNC(939)
+FUNC(940)
+FUNC(941)
+FUNC(942)
+FUNC(943)
+FUNC(944)
+FUNC(945)
+FUNC(946)
+FUNC(947)
+FUNC(948)
+FUNC(949)
+FUNC(950)
+FUNC(951)
+FUNC(952)
+FUNC(953)
+FUNC(954)
+FUNC(955)
+FUNC(956)
+FUNC(957)
+FUNC(958)
+FUNC(959)
+FUNC(960)
+FUNC(961)
+FUNC(962)
+FUNC(963)
+FUNC(964)
+FUNC(965)
+FUNC(966)
+FUNC(967)
+FUNC(968)
+FUNC(969)
+FUNC(970)
+FUNC(971)
+FUNC(972)
+FUNC(973)
+FUNC(974)
+FUNC(975)
+FUNC(976)
+FUNC(977)
+FUNC(978)
+FUNC(979)
+FUNC(980)
+FUNC(981)
+FUNC(982)
+FUNC(983)
+FUNC(984)
+FUNC(985)
+FUNC(986)
+FUNC(987)
+FUNC(988)
+FUNC(989)
+FUNC(990)
+FUNC(991)
+FUNC(992)
+FUNC(993)
+FUNC(994)
+FUNC(995)
+FUNC(996)
+FUNC(997)
+FUNC(998)
+FUNC(999)
+FUNC(1000)
+FUNC(1001)
+FUNC(1002)
+FUNC(1003)
+FUNC(1004)
+FUNC(1005)
+FUNC(1006)
+FUNC(1007)
+FUNC(1008)
+FUNC(1009)
+FUNC(1010)
+FUNC(1011)
+FUNC(1012)
+FUNC(1013)
+FUNC(1014)
+FUNC(1015)
+FUNC(1016)
+FUNC(1017)
+FUNC(1018)
+FUNC(1019)
+FUNC(1020)
+FUNC(1021)
+FUNC(1022)
+FUNC(1023)
+FUNC(1024)
+FUNC(1025)
+FUNC(1026)
+FUNC(1027)
+FUNC(1028)
+FUNC(1029)
+FUNC(1030)
+FUNC(1031)
+FUNC(1032)
+FUNC(1033)
+FUNC(1034)
+FUNC(1035)
+FUNC(1036)
+FUNC(1037)
+FUNC(1038)
+FUNC(1039)
+FUNC(1040)
+FUNC(1041)
+FUNC(1042)
+FUNC(1043)
+FUNC(1044)
+FUNC(1045)
+FUNC(1046)
+FUNC(1047)
+FUNC(1048)
+FUNC(1049)
+FUNC(1050)
+FUNC(1051)
+FUNC(1052)
+FUNC(1053)
+FUNC(1054)
+FUNC(1055)
+FUNC(1056)
+FUNC(1057)
+FUNC(1058)
+FUNC(1059)
+FUNC(1060)
+FUNC(1061)
+FUNC(1062)
+FUNC(1063)
+FUNC(1064)
+FUNC(1065)
+FUNC(1066)
+FUNC(1067)
+FUNC(1068)
+FUNC(1069)
+FUNC(1070)
+FUNC(1071)
+FUNC(1072)
+FUNC(1073)
+FUNC(1074)
+FUNC(1075)
+FUNC(1076)
+FUNC(1077)
+FUNC(1078)
+FUNC(1079)
+FUNC(1080)
+FUNC(1081)
+FUNC(1082)
+FUNC(1083)
+FUNC(1084)
+FUNC(1085)
+FUNC(1086)
+FUNC(1087)
+FUNC(1088)
+FUNC(1089)
+FUNC(1090)
+FUNC(1091)
+FUNC(1092)
+FUNC(1093)
+FUNC(1094)
+FUNC(1095)
+FUNC(1096)
+FUNC(1097)
+FUNC(1098)
+FUNC(1099)
+FUNC(1100)
+FUNC(1101)
+FUNC(1102)
+FUNC(1103)
+FUNC(1104)
+FUNC(1105)
+FUNC(1106)
+FUNC(1107)
+FUNC(1108)
+FUNC(1109)
+FUNC(1110)
+FUNC(1111)
+FUNC(1112)
+FUNC(1113)
+FUNC(1114)
+FUNC(1115)
+FUNC(1116)
+FUNC(1117)
+FUNC(1118)
+FUNC(1119)
+FUNC(1120)
+FUNC(1121)
+FUNC(1122)
+FUNC(1123)
+FUNC(1124)
+FUNC(1125)
+FUNC(1126)
+FUNC(1127)
+FUNC(1128)
+FUNC(1129)
+FUNC(1130)
+FUNC(1131)
+FUNC(1132)
+FUNC(1133)
+FUNC(1134)
+FUNC(1135)
+FUNC(1136)
+FUNC(1137)
+FUNC(1138)
+FUNC(1139)
+FUNC(1140)
+FUNC(1141)
+FUNC(1142)
+FUNC(1143)
+FUNC(1144)
+FUNC(1145)
+FUNC(1146)
+FUNC(1147)
+FUNC(1148)
+FUNC(1149)
+FUNC(1150)
+FUNC(1151)
+FUNC(1152)
+FUNC(1153)
+FUNC(1154)
+FUNC(1155)
+FUNC(1156)
+FUNC(1157)
+FUNC(1158)
+FUNC(1159)
+FUNC(1160)
+FUNC(1161)
+FUNC(1162)
+FUNC(1163)
+FUNC(1164)
+FUNC(1165)
+FUNC(1166)
+FUNC(1167)
+FUNC(1168)
+FUNC(1169)
+FUNC(1170)
+FUNC(1171)
+FUNC(1172)
+FUNC(1173)
+FUNC(1174)
+FUNC(1175)
+FUNC(1176)
+FUNC(1177)
+FUNC(1178)
+FUNC(1179)
+FUNC(1180)
+FUNC(1181)
+FUNC(1182)
+FUNC(1183)
+FUNC(1184)
+FUNC(1185)
+FUNC(1186)
+FUNC(1187)
+FUNC(1188)
+FUNC(1189)
+FUNC(1190)
+FUNC(1191)
+FUNC(1192)
+FUNC(1193)
+FUNC(1194)
+FUNC(1195)
+FUNC(1196)
+FUNC(1197)
+FUNC(1198)
+FUNC(1199)
+FUNC(1200)
+FUNC(1201)
+FUNC(1202)
+FUNC(1203)
+FUNC(1204)
+FUNC(1205)
+FUNC(1206)
+FUNC(1207)
+FUNC(1208)
+FUNC(1209)
+FUNC(1210)
+FUNC(1211)
+FUNC(1212)
+FUNC(1213)
+FUNC(1214)
+FUNC(1215)
+FUNC(1216)
+FUNC(1217)
+FUNC(1218)
+FUNC(1219)
+FUNC(1220)
+FUNC(1221)
+FUNC(1222)
+FUNC(1223)
+FUNC(1224)
+FUNC(1225)
+FUNC(1226)
+FUNC(1227)
+FUNC(1228)
+FUNC(1229)
+FUNC(1230)
+FUNC(1231)
+FUNC(1232)
+FUNC(1233)
+FUNC(1234)
+FUNC(1235)
+FUNC(1236)
+FUNC(1237)
+FUNC(1238)
+FUNC(1239)
+FUNC(1240)
+FUNC(1241)
+FUNC(1242)
+FUNC(1243)
+FUNC(1244)
+FUNC(1245)
+FUNC(1246)
+FUNC(1247)
+FUNC(1248)
+FUNC(1249)
+FUNC(1250)
+FUNC(1251)
+FUNC(1252)
+FUNC(1253)
+FUNC(1254)
+FUNC(1255)
+FUNC(1256)
+FUNC(1257)
+FUNC(1258)
+FUNC(1259)
+FUNC(1260)
+FUNC(1261)
+FUNC(1262)
+FUNC(1263)
+FUNC(1264)
+FUNC(1265)
+FUNC(1266)
+FUNC(1267)
+FUNC(1268)
+FUNC(1269)
+FUNC(1270)
+FUNC(1271)
+FUNC(1272)
+FUNC(1273)
+FUNC(1274)
+FUNC(1275)
+FUNC(1276)
+FUNC(1277)
+FUNC(1278)
+FUNC(1279)
+FUNC(1280)
+FUNC(1281)
+FUNC(1282)
+FUNC(1283)
+FUNC(1284)
+FUNC(1285)
+FUNC(1286)
+FUNC(1287)
+FUNC(1288)
+FUNC(1289)
+FUNC(1290)
+FUNC(1291)
+FUNC(1292)
+FUNC(1293)
+FUNC(1294)
+FUNC(1295)
+FUNC(1296)
+FUNC(1297)
+FUNC(1298)
+FUNC(1299)
+FUNC(1300)
+FUNC(1301)
+FUNC(1302)
+FUNC(1303)
+FUNC(1304)
+FUNC(1305)
+FUNC(1306)
+FUNC(1307)
+FUNC(1308)
+FUNC(1309)
+FUNC(1310)
+FUNC(1311)
+FUNC(1312)
+FUNC(1313)
+FUNC(1314)
+FUNC(1315)
+FUNC(1316)
+FUNC(1317)
+FUNC(1318)
+FUNC(1319)
+FUNC(1320)
+FUNC(1321)
+FUNC(1322)
+FUNC(1323)
+FUNC(1324)
+FUNC(1325)
+FUNC(1326)
+FUNC(1327)
+FUNC(1328)
+FUNC(1329)
+FUNC(1330)
+FUNC(1331)
+FUNC(1332)
+FUNC(1333)
+FUNC(1334)
+FUNC(1335)
+FUNC(1336)
+FUNC(1337)
+FUNC(1338)
+FUNC(1339)
+FUNC(1340)
+FUNC(1341)
+FUNC(1342)
+FUNC(1343)
+FUNC(1344)
+FUNC(1345)
+FUNC(1346)
+FUNC(1347)
+FUNC(1348)
+FUNC(1349)
+FUNC(1350)
+FUNC(1351)
+FUNC(1352)
+FUNC(1353)
+FUNC(1354)
+FUNC(1355)
+FUNC(1356)
+FUNC(1357)
+FUNC(1358)
+FUNC(1359)
+FUNC(1360)
+FUNC(1361)
+FUNC(1362)
+FUNC(1363)
+FUNC(1364)
+FUNC(1365)
+FUNC(1366)
+FUNC(1367)
+FUNC(1368)
+FUNC(1369)
+FUNC(1370)
+FUNC(1371)
+FUNC(1372)
+FUNC(1373)
+FUNC(1374)
+FUNC(1375)
+FUNC(1376)
+FUNC(1377)
+FUNC(1378)
+FUNC(1379)
+FUNC(1380)
+FUNC(1381)
+FUNC(1382)
+FUNC(1383)
+FUNC(1384)
+FUNC(1385)
+FUNC(1386)
+FUNC(1387)
+FUNC(1388)
+FUNC(1389)
+FUNC(1390)
+FUNC(1391)
+FUNC(1392)
+FUNC(1393)
+FUNC(1394)
+FUNC(1395)
+FUNC(1396)
+FUNC(1397)
+FUNC(1398)
+FUNC(1399)
+FUNC(1400)
+FUNC(1401)
+FUNC(1402)
+FUNC(1403)
+FUNC(1404)
+FUNC(1405)
+FUNC(1406)
+FUNC(1407)
+FUNC(1408)
+FUNC(1409)
+FUNC(1410)
+FUNC(1411)
+FUNC(1412)
+FUNC(1413)
+FUNC(1414)
+FUNC(1415)
+FUNC(1416)
+FUNC(1417)
+FUNC(1418)
+FUNC(1419)
+FUNC(1420)
+FUNC(1421)
+FUNC(1422)
+FUNC(1423)
+FUNC(1424)
+FUNC(1425)
+FUNC(1426)
+FUNC(1427)
+FUNC(1428)
+FUNC(1429)
+FUNC(1430)
+FUNC(1431)
+FUNC(1432)
+FUNC(1433)
+FUNC(1434)
+FUNC(1435)
+FUNC(1436)
+FUNC(1437)
+FUNC(1438)
+FUNC(1439)
+FUNC(1440)
+FUNC(1441)
+FUNC(1442)
+FUNC(1443)
+FUNC(1444)
+FUNC(1445)
+FUNC(1446)
+FUNC(1447)
+FUNC(1448)
+FUNC(1449)
+FUNC(1450)
+FUNC(1451)
+FUNC(1452)
+FUNC(1453)
+FUNC(1454)
+FUNC(1455)
+FUNC(1456)
+FUNC(1457)
+FUNC(1458)
+FUNC(1459)
+FUNC(1460)
+FUNC(1461)
+FUNC(1462)
+FUNC(1463)
+FUNC(1464)
+FUNC(1465)
+FUNC(1466)
+FUNC(1467)
+FUNC(1468)
+FUNC(1469)
+FUNC(1470)
+FUNC(1471)
+FUNC(1472)
+FUNC(1473)
+FUNC(1474)
+FUNC(1475)
+FUNC(1476)
+FUNC(1477)
+FUNC(1478)
+FUNC(1479)
+FUNC(1480)
+FUNC(1481)
+FUNC(1482)
+FUNC(1483)
+FUNC(1484)
+FUNC(1485)
+FUNC(1486)
+FUNC(1487)
+FUNC(1488)
+FUNC(1489)
+FUNC(1490)
+FUNC(1491)
+FUNC(1492)
+FUNC(1493)
+FUNC(1494)
+FUNC(1495)
+FUNC(1496)
+FUNC(1497)
+FUNC(1498)
+FUNC(1499)
+FUNC(1500)
+FUNC(1501)
+FUNC(1502)
+FUNC(1503)
+FUNC(1504)
+FUNC(1505)
+FUNC(1506)
+FUNC(1507)
+FUNC(1508)
+FUNC(1509)
+FUNC(1510)
+FUNC(1511)
+FUNC(1512)
+FUNC(1513)
+FUNC(1514)
+FUNC(1515)
+FUNC(1516)
+FUNC(1517)
+FUNC(1518)
+FUNC(1519)
+FUNC(1520)
+FUNC(1521)
+FUNC(1522)
+FUNC(1523)
+FUNC(1524)
+FUNC(1525)
+FUNC(1526)
+FUNC(1527)
+FUNC(1528)
+FUNC(1529)
+FUNC(1530)
+FUNC(1531)
+FUNC(1532)
+FUNC(1533)
+FUNC(1534)
+FUNC(1535)
+FUNC(1536)
+FUNC(1537)
+FUNC(1538)
+FUNC(1539)
+FUNC(1540)
+FUNC(1541)
+FUNC(1542)
+FUNC(1543)
+FUNC(1544)
+FUNC(1545)
+FUNC(1546)
+FUNC(1547)
+FUNC(1548)
+FUNC(1549)
+FUNC(1550)
+FUNC(1551)
+FUNC(1552)
+FUNC(1553)
+FUNC(1554)
+FUNC(1555)
+FUNC(1556)
+FUNC(1557)
+FUNC(1558)
+FUNC(1559)
+FUNC(1560)
+FUNC(1561)
+FUNC(1562)
+FUNC(1563)
+FUNC(1564)
+FUNC(1565)
+FUNC(1566)
+FUNC(1567)
+FUNC(1568)
+FUNC(1569)
+FUNC(1570)
+FUNC(1571)
+FUNC(1572)
+FUNC(1573)
+FUNC(1574)
+FUNC(1575)
+FUNC(1576)
+FUNC(1577)
+FUNC(1578)
+FUNC(1579)
+FUNC(1580)
+FUNC(1581)
+FUNC(1582)
+FUNC(1583)
+FUNC(1584)
+FUNC(1585)
+FUNC(1586)
+FUNC(1587)
+FUNC(1588)
+FUNC(1589)
+FUNC(1590)
+FUNC(1591)
+FUNC(1592)
+FUNC(1593)
+FUNC(1594)
+FUNC(1595)
+FUNC(1596)
+FUNC(1597)
+FUNC(1598)
+FUNC(1599)
+FUNC(1600)
+FUNC(1601)
+FUNC(1602)
+FUNC(1603)
+FUNC(1604)
+FUNC(1605)
+FUNC(1606)
+FUNC(1607)
+FUNC(1608)
+FUNC(1609)
+FUNC(1610)
+FUNC(1611)
+FUNC(1612)
+FUNC(1613)
+FUNC(1614)
+FUNC(1615)
+FUNC(1616)
+FUNC(1617)
+FUNC(1618)
+FUNC(1619)
+FUNC(1620)
+FUNC(1621)
+FUNC(1622)
+FUNC(1623)
+FUNC(1624)
+FUNC(1625)
+FUNC(1626)
+FUNC(1627)
+FUNC(1628)
+FUNC(1629)
+FUNC(1630)
+FUNC(1631)
+FUNC(1632)
+FUNC(1633)
+FUNC(1634)
+FUNC(1635)
+FUNC(1636)
+FUNC(1637)
+FUNC(1638)
+FUNC(1639)
+FUNC(1640)
+FUNC(1641)
+FUNC(1642)
+FUNC(1643)
+FUNC(1644)
+FUNC(1645)
+FUNC(1646)
+FUNC(1647)
+FUNC(1648)
+FUNC(1649)
+FUNC(1650)
+FUNC(1651)
+FUNC(1652)
+FUNC(1653)
+FUNC(1654)
+FUNC(1655)
+FUNC(1656)
+FUNC(1657)
+FUNC(1658)
+FUNC(1659)
+FUNC(1660)
+FUNC(1661)
+FUNC(1662)
+FUNC(1663)
+FUNC(1664)
+FUNC(1665)
+FUNC(1666)
+FUNC(1667)
+FUNC(1668)
+FUNC(1669)
+FUNC(1670)
+FUNC(1671)
+FUNC(1672)
+FUNC(1673)
+FUNC(1674)
+FUNC(1675)
+FUNC(1676)
+FUNC(1677)
+FUNC(1678)
+FUNC(1679)
+FUNC(1680)
+FUNC(1681)
+FUNC(1682)
+FUNC(1683)
+FUNC(1684)
+FUNC(1685)
+FUNC(1686)
+FUNC(1687)
+FUNC(1688)
+FUNC(1689)
+FUNC(1690)
+FUNC(1691)
+FUNC(1692)
+FUNC(1693)
+FUNC(1694)
+FUNC(1695)
+FUNC(1696)
+FUNC(1697)
+FUNC(1698)
+FUNC(1699)
+FUNC(1700)
+FUNC(1701)
+FUNC(1702)
+FUNC(1703)
+FUNC(1704)
+FUNC(1705)
+FUNC(1706)
+FUNC(1707)
+FUNC(1708)
+FUNC(1709)
+FUNC(1710)
+FUNC(1711)
+FUNC(1712)
+FUNC(1713)
+FUNC(1714)
+FUNC(1715)
+FUNC(1716)
+FUNC(1717)
+FUNC(1718)
+FUNC(1719)
+FUNC(1720)
+FUNC(1721)
+FUNC(1722)
+FUNC(1723)
+FUNC(1724)
+FUNC(1725)
+FUNC(1726)
+FUNC(1727)
+FUNC(1728)
+FUNC(1729)
+FUNC(1730)
+FUNC(1731)
+FUNC(1732)
+FUNC(1733)
+FUNC(1734)
+FUNC(1735)
+FUNC(1736)
+FUNC(1737)
+FUNC(1738)
+FUNC(1739)
+FUNC(1740)
+FUNC(1741)
+FUNC(1742)
+FUNC(1743)
+FUNC(1744)
+FUNC(1745)
+FUNC(1746)
+FUNC(1747)
+FUNC(1748)
+FUNC(1749)
+FUNC(1750)
+FUNC(1751)
+FUNC(1752)
+FUNC(1753)
+FUNC(1754)
+FUNC(1755)
+FUNC(1756)
+FUNC(1757)
+FUNC(1758)
+FUNC(1759)
+FUNC(1760)
+FUNC(1761)
+FUNC(1762)
+FUNC(1763)
+FUNC(1764)
+FUNC(1765)
+FUNC(1766)
+FUNC(1767)
+FUNC(1768)
+FUNC(1769)
+FUNC(1770)
+FUNC(1771)
+FUNC(1772)
+FUNC(1773)
+FUNC(1774)
+FUNC(1775)
+FUNC(1776)
+FUNC(1777)
+FUNC(1778)
+FUNC(1779)
+FUNC(1780)
+FUNC(1781)
+FUNC(1782)
+FUNC(1783)
+FUNC(1784)
+FUNC(1785)
+FUNC(1786)
+FUNC(1787)
+FUNC(1788)
+FUNC(1789)
+FUNC(1790)
+FUNC(1791)
+FUNC(1792)
+FUNC(1793)
+FUNC(1794)
+FUNC(1795)
+FUNC(1796)
+FUNC(1797)
+FUNC(1798)
+FUNC(1799)
+FUNC(1800)
+FUNC(1801)
+FUNC(1802)
+FUNC(1803)
+FUNC(1804)
+FUNC(1805)
+FUNC(1806)
+FUNC(1807)
+FUNC(1808)
+FUNC(1809)
+FUNC(1810)
+FUNC(1811)
+FUNC(1812)
+FUNC(1813)
+FUNC(1814)
+FUNC(1815)
+FUNC(1816)
+FUNC(1817)
+FUNC(1818)
+FUNC(1819)
+FUNC(1820)
+FUNC(1821)
+FUNC(1822)
+FUNC(1823)
+FUNC(1824)
+FUNC(1825)
+FUNC(1826)
+FUNC(1827)
+FUNC(1828)
+FUNC(1829)
+FUNC(1830)
+FUNC(1831)
+FUNC(1832)
+FUNC(1833)
+FUNC(1834)
+FUNC(1835)
+FUNC(1836)
+FUNC(1837)
+FUNC(1838)
+FUNC(1839)
+FUNC(1840)
+FUNC(1841)
+FUNC(1842)
+FUNC(1843)
+FUNC(1844)
+FUNC(1845)
+FUNC(1846)
+FUNC(1847)
+FUNC(1848)
+FUNC(1849)
+FUNC(1850)
+FUNC(1851)
+FUNC(1852)
+FUNC(1853)
+FUNC(1854)
+FUNC(1855)
+FUNC(1856)
+FUNC(1857)
+FUNC(1858)
+FUNC(1859)
+FUNC(1860)
+FUNC(1861)
+FUNC(1862)
+FUNC(1863)
+FUNC(1864)
+FUNC(1865)
+FUNC(1866)
+FUNC(1867)
+FUNC(1868)
+FUNC(1869)
+FUNC(1870)
+FUNC(1871)
+FUNC(1872)
+FUNC(1873)
+FUNC(1874)
+FUNC(1875)
+FUNC(1876)
+FUNC(1877)
+FUNC(1878)
+FUNC(1879)
+FUNC(1880)
+FUNC(1881)
+FUNC(1882)
+FUNC(1883)
+FUNC(1884)
+FUNC(1885)
+FUNC(1886)
+FUNC(1887)
+FUNC(1888)
+FUNC(1889)
+FUNC(1890)
+FUNC(1891)
+FUNC(1892)
+FUNC(1893)
+FUNC(1894)
+FUNC(1895)
+FUNC(1896)
+FUNC(1897)
+FUNC(1898)
+FUNC(1899)
+FUNC(1900)
+FUNC(1901)
+FUNC(1902)
+FUNC(1903)
+FUNC(1904)
+FUNC(1905)
+FUNC(1906)
+FUNC(1907)
+FUNC(1908)
+FUNC(1909)
+FUNC(1910)
+FUNC(1911)
+FUNC(1912)
+FUNC(1913)
+FUNC(1914)
+FUNC(1915)
+FUNC(1916)
+FUNC(1917)
+FUNC(1918)
+FUNC(1919)
+FUNC(1920)
+FUNC(1921)
+FUNC(1922)
+FUNC(1923)
+FUNC(1924)
+FUNC(1925)
+FUNC(1926)
+FUNC(1927)
+FUNC(1928)
+FUNC(1929)
+FUNC(1930)
+FUNC(1931)
+FUNC(1932)
+FUNC(1933)
+FUNC(1934)
+FUNC(1935)
+FUNC(1936)
+FUNC(1937)
+FUNC(1938)
+FUNC(1939)
+FUNC(1940)
+FUNC(1941)
+FUNC(1942)
+FUNC(1943)
+FUNC(1944)
+FUNC(1945)
+FUNC(1946)
+FUNC(1947)
+FUNC(1948)
+FUNC(1949)
+FUNC(1950)
+FUNC(1951)
+FUNC(1952)
+FUNC(1953)
+FUNC(1954)
+FUNC(1955)
+FUNC(1956)
+FUNC(1957)
+FUNC(1958)
+FUNC(1959)
+FUNC(1960)
+FUNC(1961)
+FUNC(1962)
+FUNC(1963)
+FUNC(1964)
+FUNC(1965)
+FUNC(1966)
+FUNC(1967)
+FUNC(1968)
+FUNC(1969)
+FUNC(1970)
+FUNC(1971)
+FUNC(1972)
+FUNC(1973)
+FUNC(1974)
+FUNC(1975)
+FUNC(1976)
+FUNC(1977)
+FUNC(1978)
+FUNC(1979)
+FUNC(1980)
+FUNC(1981)
+FUNC(1982)
+FUNC(1983)
+FUNC(1984)
+FUNC(1985)
+FUNC(1986)
+FUNC(1987)
+FUNC(1988)
+FUNC(1989)
+FUNC(1990)
+FUNC(1991)
+FUNC(1992)
+FUNC(1993)
+FUNC(1994)
+FUNC(1995)
+FUNC(1996)
+FUNC(1997)
+FUNC(1998)
+FUNC(1999)
+FUNC(2000)
--- a/sbsv2/raptor/lib/flm/test/exeabiv2_4/exeabiv2_4.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/exeabiv2_4/exeabiv2_4.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,46 +1,46 @@
-#
-# 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: 
-#
-##
-## Test 1 - build an ARM E32 EXE on Linux
-## parameters relevant to the test.
-##
-
-
-## Purpose:
-## This is used to gauge perfomance 
-## At least one "large" input file is built
-## The input file has no dependencies so it really is just something for the compiler to "chew"
-
-
-# Pull tools
-include $(FLMHOME)/flmtools.mk
-
-$(call vsave,OUTPUTPATH SOURCEPATH CDEFS SYSTEMINCLUDE)
-# Pull in defaults for building test executables
-include $(FLMTESTHOME)/exeabiv2_defaults.mk
-
-
-TARGET:=exeabiv2_4
-CDEFS:=$(CDEFS) __TESTNAME__=\"exeabiv2_4\"
-OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)
-SOURCEPATH:=$(SOURCEPATH)/exeabiv2_4
-SOURCEFILES:=$(SOURCEPATH)/test.cpp $(SOURCEPATH)/test_big.cpp
-SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(FLMTESTHOME)/include
-UID3:=0x000004
-
-include $(FLMHOME)/$(FLM)
-
-$(call vrestore)
+#
+# 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: 
+#
+##
+## Test 1 - build an ARM E32 EXE on Linux
+## parameters relevant to the test.
+##
+
+
+## Purpose:
+## This is used to gauge perfomance 
+## At least one "large" input file is built
+## The input file has no dependencies so it really is just something for the compiler to "chew"
+
+
+# Pull tools
+include $(FLMHOME)/flmtools.mk
+
+$(call vsave,OUTPUTPATH SOURCEPATH CDEFS SYSTEMINCLUDE)
+# Pull in defaults for building test executables
+include $(FLMTESTHOME)/exeabiv2_defaults.mk
+
+
+TARGET:=exeabiv2_4
+CDEFS:=$(CDEFS) __TESTNAME__=\"exeabiv2_4\"
+OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)
+SOURCEPATH:=$(SOURCEPATH)/exeabiv2_4
+SOURCEFILES:=$(SOURCEPATH)/test.cpp $(SOURCEPATH)/test_big.cpp
+SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(FLMTESTHOME)/include
+UID3:=0x000004
+
+include $(FLMHOME)/$(FLM)
+
+$(call vrestore)
--- a/sbsv2/raptor/lib/flm/test/exeabiv2_4/test.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/exeabiv2_4/test.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,27 +1,27 @@
-/*
-* 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: 
-*
-*/
-
-#include <e32def.h>
-
-int i=1;
-
-extern int function_1(void);
-TInt E32Main(void)
-{
-	function_1();
-	return 0;
-}
+/*
+* 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: 
+*
+*/
+
+#include <e32def.h>
+
+int i=1;
+
+extern int function_1(void);
+TInt E32Main(void)
+{
+	function_1();
+	return 0;
+}
--- a/sbsv2/raptor/lib/flm/test/exeabiv2_4/test_big.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/exeabiv2_4/test_big.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,2045 +1,2045 @@
-/*
-* 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: 
-*
-*/
-/* 
-This is jsut some "compiler fibre" for the compiler to chew
-on as part of a compilation performace test
-*/
-
-#define FUNC(VARIABLE)	\
-int function_##VARIABLE(void)	\
-{	\
-	int x,y,z;	\
-	x=VARIABLE+30* 10-1;	\
-	y=x*4;	\
-	\
-	\
-	x=y+1;	\
-	\
-	int a[VARIABLE];	\
-	\
-	\
-	\
-	for (z=0; z < 1000+VARIABLE; z++)	\
-	{	\
-		x+=a[z];		\
-	}	\
-	\
-	return x;	\
-}
-
-
-
-FUNC(1)
-FUNC(2)
-FUNC(3)
-FUNC(4)
-FUNC(5)
-FUNC(6)
-FUNC(7)
-FUNC(8)
-FUNC(9)
-FUNC(10)
-FUNC(11)
-FUNC(12)
-FUNC(13)
-FUNC(14)
-FUNC(15)
-FUNC(16)
-FUNC(17)
-FUNC(18)
-FUNC(19)
-FUNC(20)
-FUNC(21)
-FUNC(22)
-FUNC(23)
-FUNC(24)
-FUNC(25)
-FUNC(26)
-FUNC(27)
-FUNC(28)
-FUNC(29)
-FUNC(30)
-FUNC(31)
-FUNC(32)
-FUNC(33)
-FUNC(34)
-FUNC(35)
-FUNC(36)
-FUNC(37)
-FUNC(38)
-FUNC(39)
-FUNC(40)
-FUNC(41)
-FUNC(42)
-FUNC(43)
-FUNC(44)
-FUNC(45)
-FUNC(46)
-FUNC(47)
-FUNC(48)
-FUNC(49)
-FUNC(50)
-FUNC(51)
-FUNC(52)
-FUNC(53)
-FUNC(54)
-FUNC(55)
-FUNC(56)
-FUNC(57)
-FUNC(58)
-FUNC(59)
-FUNC(60)
-FUNC(61)
-FUNC(62)
-FUNC(63)
-FUNC(64)
-FUNC(65)
-FUNC(66)
-FUNC(67)
-FUNC(68)
-FUNC(69)
-FUNC(70)
-FUNC(71)
-FUNC(72)
-FUNC(73)
-FUNC(74)
-FUNC(75)
-FUNC(76)
-FUNC(77)
-FUNC(78)
-FUNC(79)
-FUNC(80)
-FUNC(81)
-FUNC(82)
-FUNC(83)
-FUNC(84)
-FUNC(85)
-FUNC(86)
-FUNC(87)
-FUNC(88)
-FUNC(89)
-FUNC(90)
-FUNC(91)
-FUNC(92)
-FUNC(93)
-FUNC(94)
-FUNC(95)
-FUNC(96)
-FUNC(97)
-FUNC(98)
-FUNC(99)
-FUNC(100)
-FUNC(101)
-FUNC(102)
-FUNC(103)
-FUNC(104)
-FUNC(105)
-FUNC(106)
-FUNC(107)
-FUNC(108)
-FUNC(109)
-FUNC(110)
-FUNC(111)
-FUNC(112)
-FUNC(113)
-FUNC(114)
-FUNC(115)
-FUNC(116)
-FUNC(117)
-FUNC(118)
-FUNC(119)
-FUNC(120)
-FUNC(121)
-FUNC(122)
-FUNC(123)
-FUNC(124)
-FUNC(125)
-FUNC(126)
-FUNC(127)
-FUNC(128)
-FUNC(129)
-FUNC(130)
-FUNC(131)
-FUNC(132)
-FUNC(133)
-FUNC(134)
-FUNC(135)
-FUNC(136)
-FUNC(137)
-FUNC(138)
-FUNC(139)
-FUNC(140)
-FUNC(141)
-FUNC(142)
-FUNC(143)
-FUNC(144)
-FUNC(145)
-FUNC(146)
-FUNC(147)
-FUNC(148)
-FUNC(149)
-FUNC(150)
-FUNC(151)
-FUNC(152)
-FUNC(153)
-FUNC(154)
-FUNC(155)
-FUNC(156)
-FUNC(157)
-FUNC(158)
-FUNC(159)
-FUNC(160)
-FUNC(161)
-FUNC(162)
-FUNC(163)
-FUNC(164)
-FUNC(165)
-FUNC(166)
-FUNC(167)
-FUNC(168)
-FUNC(169)
-FUNC(170)
-FUNC(171)
-FUNC(172)
-FUNC(173)
-FUNC(174)
-FUNC(175)
-FUNC(176)
-FUNC(177)
-FUNC(178)
-FUNC(179)
-FUNC(180)
-FUNC(181)
-FUNC(182)
-FUNC(183)
-FUNC(184)
-FUNC(185)
-FUNC(186)
-FUNC(187)
-FUNC(188)
-FUNC(189)
-FUNC(190)
-FUNC(191)
-FUNC(192)
-FUNC(193)
-FUNC(194)
-FUNC(195)
-FUNC(196)
-FUNC(197)
-FUNC(198)
-FUNC(199)
-FUNC(200)
-FUNC(201)
-FUNC(202)
-FUNC(203)
-FUNC(204)
-FUNC(205)
-FUNC(206)
-FUNC(207)
-FUNC(208)
-FUNC(209)
-FUNC(210)
-FUNC(211)
-FUNC(212)
-FUNC(213)
-FUNC(214)
-FUNC(215)
-FUNC(216)
-FUNC(217)
-FUNC(218)
-FUNC(219)
-FUNC(220)
-FUNC(221)
-FUNC(222)
-FUNC(223)
-FUNC(224)
-FUNC(225)
-FUNC(226)
-FUNC(227)
-FUNC(228)
-FUNC(229)
-FUNC(230)
-FUNC(231)
-FUNC(232)
-FUNC(233)
-FUNC(234)
-FUNC(235)
-FUNC(236)
-FUNC(237)
-FUNC(238)
-FUNC(239)
-FUNC(240)
-FUNC(241)
-FUNC(242)
-FUNC(243)
-FUNC(244)
-FUNC(245)
-FUNC(246)
-FUNC(247)
-FUNC(248)
-FUNC(249)
-FUNC(250)
-FUNC(251)
-FUNC(252)
-FUNC(253)
-FUNC(254)
-FUNC(255)
-FUNC(256)
-FUNC(257)
-FUNC(258)
-FUNC(259)
-FUNC(260)
-FUNC(261)
-FUNC(262)
-FUNC(263)
-FUNC(264)
-FUNC(265)
-FUNC(266)
-FUNC(267)
-FUNC(268)
-FUNC(269)
-FUNC(270)
-FUNC(271)
-FUNC(272)
-FUNC(273)
-FUNC(274)
-FUNC(275)
-FUNC(276)
-FUNC(277)
-FUNC(278)
-FUNC(279)
-FUNC(280)
-FUNC(281)
-FUNC(282)
-FUNC(283)
-FUNC(284)
-FUNC(285)
-FUNC(286)
-FUNC(287)
-FUNC(288)
-FUNC(289)
-FUNC(290)
-FUNC(291)
-FUNC(292)
-FUNC(293)
-FUNC(294)
-FUNC(295)
-FUNC(296)
-FUNC(297)
-FUNC(298)
-FUNC(299)
-FUNC(300)
-FUNC(301)
-FUNC(302)
-FUNC(303)
-FUNC(304)
-FUNC(305)
-FUNC(306)
-FUNC(307)
-FUNC(308)
-FUNC(309)
-FUNC(310)
-FUNC(311)
-FUNC(312)
-FUNC(313)
-FUNC(314)
-FUNC(315)
-FUNC(316)
-FUNC(317)
-FUNC(318)
-FUNC(319)
-FUNC(320)
-FUNC(321)
-FUNC(322)
-FUNC(323)
-FUNC(324)
-FUNC(325)
-FUNC(326)
-FUNC(327)
-FUNC(328)
-FUNC(329)
-FUNC(330)
-FUNC(331)
-FUNC(332)
-FUNC(333)
-FUNC(334)
-FUNC(335)
-FUNC(336)
-FUNC(337)
-FUNC(338)
-FUNC(339)
-FUNC(340)
-FUNC(341)
-FUNC(342)
-FUNC(343)
-FUNC(344)
-FUNC(345)
-FUNC(346)
-FUNC(347)
-FUNC(348)
-FUNC(349)
-FUNC(350)
-FUNC(351)
-FUNC(352)
-FUNC(353)
-FUNC(354)
-FUNC(355)
-FUNC(356)
-FUNC(357)
-FUNC(358)
-FUNC(359)
-FUNC(360)
-FUNC(361)
-FUNC(362)
-FUNC(363)
-FUNC(364)
-FUNC(365)
-FUNC(366)
-FUNC(367)
-FUNC(368)
-FUNC(369)
-FUNC(370)
-FUNC(371)
-FUNC(372)
-FUNC(373)
-FUNC(374)
-FUNC(375)
-FUNC(376)
-FUNC(377)
-FUNC(378)
-FUNC(379)
-FUNC(380)
-FUNC(381)
-FUNC(382)
-FUNC(383)
-FUNC(384)
-FUNC(385)
-FUNC(386)
-FUNC(387)
-FUNC(388)
-FUNC(389)
-FUNC(390)
-FUNC(391)
-FUNC(392)
-FUNC(393)
-FUNC(394)
-FUNC(395)
-FUNC(396)
-FUNC(397)
-FUNC(398)
-FUNC(399)
-FUNC(400)
-FUNC(401)
-FUNC(402)
-FUNC(403)
-FUNC(404)
-FUNC(405)
-FUNC(406)
-FUNC(407)
-FUNC(408)
-FUNC(409)
-FUNC(410)
-FUNC(411)
-FUNC(412)
-FUNC(413)
-FUNC(414)
-FUNC(415)
-FUNC(416)
-FUNC(417)
-FUNC(418)
-FUNC(419)
-FUNC(420)
-FUNC(421)
-FUNC(422)
-FUNC(423)
-FUNC(424)
-FUNC(425)
-FUNC(426)
-FUNC(427)
-FUNC(428)
-FUNC(429)
-FUNC(430)
-FUNC(431)
-FUNC(432)
-FUNC(433)
-FUNC(434)
-FUNC(435)
-FUNC(436)
-FUNC(437)
-FUNC(438)
-FUNC(439)
-FUNC(440)
-FUNC(441)
-FUNC(442)
-FUNC(443)
-FUNC(444)
-FUNC(445)
-FUNC(446)
-FUNC(447)
-FUNC(448)
-FUNC(449)
-FUNC(450)
-FUNC(451)
-FUNC(452)
-FUNC(453)
-FUNC(454)
-FUNC(455)
-FUNC(456)
-FUNC(457)
-FUNC(458)
-FUNC(459)
-FUNC(460)
-FUNC(461)
-FUNC(462)
-FUNC(463)
-FUNC(464)
-FUNC(465)
-FUNC(466)
-FUNC(467)
-FUNC(468)
-FUNC(469)
-FUNC(470)
-FUNC(471)
-FUNC(472)
-FUNC(473)
-FUNC(474)
-FUNC(475)
-FUNC(476)
-FUNC(477)
-FUNC(478)
-FUNC(479)
-FUNC(480)
-FUNC(481)
-FUNC(482)
-FUNC(483)
-FUNC(484)
-FUNC(485)
-FUNC(486)
-FUNC(487)
-FUNC(488)
-FUNC(489)
-FUNC(490)
-FUNC(491)
-FUNC(492)
-FUNC(493)
-FUNC(494)
-FUNC(495)
-FUNC(496)
-FUNC(497)
-FUNC(498)
-FUNC(499)
-FUNC(500)
-FUNC(501)
-FUNC(502)
-FUNC(503)
-FUNC(504)
-FUNC(505)
-FUNC(506)
-FUNC(507)
-FUNC(508)
-FUNC(509)
-FUNC(510)
-FUNC(511)
-FUNC(512)
-FUNC(513)
-FUNC(514)
-FUNC(515)
-FUNC(516)
-FUNC(517)
-FUNC(518)
-FUNC(519)
-FUNC(520)
-FUNC(521)
-FUNC(522)
-FUNC(523)
-FUNC(524)
-FUNC(525)
-FUNC(526)
-FUNC(527)
-FUNC(528)
-FUNC(529)
-FUNC(530)
-FUNC(531)
-FUNC(532)
-FUNC(533)
-FUNC(534)
-FUNC(535)
-FUNC(536)
-FUNC(537)
-FUNC(538)
-FUNC(539)
-FUNC(540)
-FUNC(541)
-FUNC(542)
-FUNC(543)
-FUNC(544)
-FUNC(545)
-FUNC(546)
-FUNC(547)
-FUNC(548)
-FUNC(549)
-FUNC(550)
-FUNC(551)
-FUNC(552)
-FUNC(553)
-FUNC(554)
-FUNC(555)
-FUNC(556)
-FUNC(557)
-FUNC(558)
-FUNC(559)
-FUNC(560)
-FUNC(561)
-FUNC(562)
-FUNC(563)
-FUNC(564)
-FUNC(565)
-FUNC(566)
-FUNC(567)
-FUNC(568)
-FUNC(569)
-FUNC(570)
-FUNC(571)
-FUNC(572)
-FUNC(573)
-FUNC(574)
-FUNC(575)
-FUNC(576)
-FUNC(577)
-FUNC(578)
-FUNC(579)
-FUNC(580)
-FUNC(581)
-FUNC(582)
-FUNC(583)
-FUNC(584)
-FUNC(585)
-FUNC(586)
-FUNC(587)
-FUNC(588)
-FUNC(589)
-FUNC(590)
-FUNC(591)
-FUNC(592)
-FUNC(593)
-FUNC(594)
-FUNC(595)
-FUNC(596)
-FUNC(597)
-FUNC(598)
-FUNC(599)
-FUNC(600)
-FUNC(601)
-FUNC(602)
-FUNC(603)
-FUNC(604)
-FUNC(605)
-FUNC(606)
-FUNC(607)
-FUNC(608)
-FUNC(609)
-FUNC(610)
-FUNC(611)
-FUNC(612)
-FUNC(613)
-FUNC(614)
-FUNC(615)
-FUNC(616)
-FUNC(617)
-FUNC(618)
-FUNC(619)
-FUNC(620)
-FUNC(621)
-FUNC(622)
-FUNC(623)
-FUNC(624)
-FUNC(625)
-FUNC(626)
-FUNC(627)
-FUNC(628)
-FUNC(629)
-FUNC(630)
-FUNC(631)
-FUNC(632)
-FUNC(633)
-FUNC(634)
-FUNC(635)
-FUNC(636)
-FUNC(637)
-FUNC(638)
-FUNC(639)
-FUNC(640)
-FUNC(641)
-FUNC(642)
-FUNC(643)
-FUNC(644)
-FUNC(645)
-FUNC(646)
-FUNC(647)
-FUNC(648)
-FUNC(649)
-FUNC(650)
-FUNC(651)
-FUNC(652)
-FUNC(653)
-FUNC(654)
-FUNC(655)
-FUNC(656)
-FUNC(657)
-FUNC(658)
-FUNC(659)
-FUNC(660)
-FUNC(661)
-FUNC(662)
-FUNC(663)
-FUNC(664)
-FUNC(665)
-FUNC(666)
-FUNC(667)
-FUNC(668)
-FUNC(669)
-FUNC(670)
-FUNC(671)
-FUNC(672)
-FUNC(673)
-FUNC(674)
-FUNC(675)
-FUNC(676)
-FUNC(677)
-FUNC(678)
-FUNC(679)
-FUNC(680)
-FUNC(681)
-FUNC(682)
-FUNC(683)
-FUNC(684)
-FUNC(685)
-FUNC(686)
-FUNC(687)
-FUNC(688)
-FUNC(689)
-FUNC(690)
-FUNC(691)
-FUNC(692)
-FUNC(693)
-FUNC(694)
-FUNC(695)
-FUNC(696)
-FUNC(697)
-FUNC(698)
-FUNC(699)
-FUNC(700)
-FUNC(701)
-FUNC(702)
-FUNC(703)
-FUNC(704)
-FUNC(705)
-FUNC(706)
-FUNC(707)
-FUNC(708)
-FUNC(709)
-FUNC(710)
-FUNC(711)
-FUNC(712)
-FUNC(713)
-FUNC(714)
-FUNC(715)
-FUNC(716)
-FUNC(717)
-FUNC(718)
-FUNC(719)
-FUNC(720)
-FUNC(721)
-FUNC(722)
-FUNC(723)
-FUNC(724)
-FUNC(725)
-FUNC(726)
-FUNC(727)
-FUNC(728)
-FUNC(729)
-FUNC(730)
-FUNC(731)
-FUNC(732)
-FUNC(733)
-FUNC(734)
-FUNC(735)
-FUNC(736)
-FUNC(737)
-FUNC(738)
-FUNC(739)
-FUNC(740)
-FUNC(741)
-FUNC(742)
-FUNC(743)
-FUNC(744)
-FUNC(745)
-FUNC(746)
-FUNC(747)
-FUNC(748)
-FUNC(749)
-FUNC(750)
-FUNC(751)
-FUNC(752)
-FUNC(753)
-FUNC(754)
-FUNC(755)
-FUNC(756)
-FUNC(757)
-FUNC(758)
-FUNC(759)
-FUNC(760)
-FUNC(761)
-FUNC(762)
-FUNC(763)
-FUNC(764)
-FUNC(765)
-FUNC(766)
-FUNC(767)
-FUNC(768)
-FUNC(769)
-FUNC(770)
-FUNC(771)
-FUNC(772)
-FUNC(773)
-FUNC(774)
-FUNC(775)
-FUNC(776)
-FUNC(777)
-FUNC(778)
-FUNC(779)
-FUNC(780)
-FUNC(781)
-FUNC(782)
-FUNC(783)
-FUNC(784)
-FUNC(785)
-FUNC(786)
-FUNC(787)
-FUNC(788)
-FUNC(789)
-FUNC(790)
-FUNC(791)
-FUNC(792)
-FUNC(793)
-FUNC(794)
-FUNC(795)
-FUNC(796)
-FUNC(797)
-FUNC(798)
-FUNC(799)
-FUNC(800)
-FUNC(801)
-FUNC(802)
-FUNC(803)
-FUNC(804)
-FUNC(805)
-FUNC(806)
-FUNC(807)
-FUNC(808)
-FUNC(809)
-FUNC(810)
-FUNC(811)
-FUNC(812)
-FUNC(813)
-FUNC(814)
-FUNC(815)
-FUNC(816)
-FUNC(817)
-FUNC(818)
-FUNC(819)
-FUNC(820)
-FUNC(821)
-FUNC(822)
-FUNC(823)
-FUNC(824)
-FUNC(825)
-FUNC(826)
-FUNC(827)
-FUNC(828)
-FUNC(829)
-FUNC(830)
-FUNC(831)
-FUNC(832)
-FUNC(833)
-FUNC(834)
-FUNC(835)
-FUNC(836)
-FUNC(837)
-FUNC(838)
-FUNC(839)
-FUNC(840)
-FUNC(841)
-FUNC(842)
-FUNC(843)
-FUNC(844)
-FUNC(845)
-FUNC(846)
-FUNC(847)
-FUNC(848)
-FUNC(849)
-FUNC(850)
-FUNC(851)
-FUNC(852)
-FUNC(853)
-FUNC(854)
-FUNC(855)
-FUNC(856)
-FUNC(857)
-FUNC(858)
-FUNC(859)
-FUNC(860)
-FUNC(861)
-FUNC(862)
-FUNC(863)
-FUNC(864)
-FUNC(865)
-FUNC(866)
-FUNC(867)
-FUNC(868)
-FUNC(869)
-FUNC(870)
-FUNC(871)
-FUNC(872)
-FUNC(873)
-FUNC(874)
-FUNC(875)
-FUNC(876)
-FUNC(877)
-FUNC(878)
-FUNC(879)
-FUNC(880)
-FUNC(881)
-FUNC(882)
-FUNC(883)
-FUNC(884)
-FUNC(885)
-FUNC(886)
-FUNC(887)
-FUNC(888)
-FUNC(889)
-FUNC(890)
-FUNC(891)
-FUNC(892)
-FUNC(893)
-FUNC(894)
-FUNC(895)
-FUNC(896)
-FUNC(897)
-FUNC(898)
-FUNC(899)
-FUNC(900)
-FUNC(901)
-FUNC(902)
-FUNC(903)
-FUNC(904)
-FUNC(905)
-FUNC(906)
-FUNC(907)
-FUNC(908)
-FUNC(909)
-FUNC(910)
-FUNC(911)
-FUNC(912)
-FUNC(913)
-FUNC(914)
-FUNC(915)
-FUNC(916)
-FUNC(917)
-FUNC(918)
-FUNC(919)
-FUNC(920)
-FUNC(921)
-FUNC(922)
-FUNC(923)
-FUNC(924)
-FUNC(925)
-FUNC(926)
-FUNC(927)
-FUNC(928)
-FUNC(929)
-FUNC(930)
-FUNC(931)
-FUNC(932)
-FUNC(933)
-FUNC(934)
-FUNC(935)
-FUNC(936)
-FUNC(937)
-FUNC(938)
-FUNC(939)
-FUNC(940)
-FUNC(941)
-FUNC(942)
-FUNC(943)
-FUNC(944)
-FUNC(945)
-FUNC(946)
-FUNC(947)
-FUNC(948)
-FUNC(949)
-FUNC(950)
-FUNC(951)
-FUNC(952)
-FUNC(953)
-FUNC(954)
-FUNC(955)
-FUNC(956)
-FUNC(957)
-FUNC(958)
-FUNC(959)
-FUNC(960)
-FUNC(961)
-FUNC(962)
-FUNC(963)
-FUNC(964)
-FUNC(965)
-FUNC(966)
-FUNC(967)
-FUNC(968)
-FUNC(969)
-FUNC(970)
-FUNC(971)
-FUNC(972)
-FUNC(973)
-FUNC(974)
-FUNC(975)
-FUNC(976)
-FUNC(977)
-FUNC(978)
-FUNC(979)
-FUNC(980)
-FUNC(981)
-FUNC(982)
-FUNC(983)
-FUNC(984)
-FUNC(985)
-FUNC(986)
-FUNC(987)
-FUNC(988)
-FUNC(989)
-FUNC(990)
-FUNC(991)
-FUNC(992)
-FUNC(993)
-FUNC(994)
-FUNC(995)
-FUNC(996)
-FUNC(997)
-FUNC(998)
-FUNC(999)
-FUNC(1000)
-FUNC(1001)
-FUNC(1002)
-FUNC(1003)
-FUNC(1004)
-FUNC(1005)
-FUNC(1006)
-FUNC(1007)
-FUNC(1008)
-FUNC(1009)
-FUNC(1010)
-FUNC(1011)
-FUNC(1012)
-FUNC(1013)
-FUNC(1014)
-FUNC(1015)
-FUNC(1016)
-FUNC(1017)
-FUNC(1018)
-FUNC(1019)
-FUNC(1020)
-FUNC(1021)
-FUNC(1022)
-FUNC(1023)
-FUNC(1024)
-FUNC(1025)
-FUNC(1026)
-FUNC(1027)
-FUNC(1028)
-FUNC(1029)
-FUNC(1030)
-FUNC(1031)
-FUNC(1032)
-FUNC(1033)
-FUNC(1034)
-FUNC(1035)
-FUNC(1036)
-FUNC(1037)
-FUNC(1038)
-FUNC(1039)
-FUNC(1040)
-FUNC(1041)
-FUNC(1042)
-FUNC(1043)
-FUNC(1044)
-FUNC(1045)
-FUNC(1046)
-FUNC(1047)
-FUNC(1048)
-FUNC(1049)
-FUNC(1050)
-FUNC(1051)
-FUNC(1052)
-FUNC(1053)
-FUNC(1054)
-FUNC(1055)
-FUNC(1056)
-FUNC(1057)
-FUNC(1058)
-FUNC(1059)
-FUNC(1060)
-FUNC(1061)
-FUNC(1062)
-FUNC(1063)
-FUNC(1064)
-FUNC(1065)
-FUNC(1066)
-FUNC(1067)
-FUNC(1068)
-FUNC(1069)
-FUNC(1070)
-FUNC(1071)
-FUNC(1072)
-FUNC(1073)
-FUNC(1074)
-FUNC(1075)
-FUNC(1076)
-FUNC(1077)
-FUNC(1078)
-FUNC(1079)
-FUNC(1080)
-FUNC(1081)
-FUNC(1082)
-FUNC(1083)
-FUNC(1084)
-FUNC(1085)
-FUNC(1086)
-FUNC(1087)
-FUNC(1088)
-FUNC(1089)
-FUNC(1090)
-FUNC(1091)
-FUNC(1092)
-FUNC(1093)
-FUNC(1094)
-FUNC(1095)
-FUNC(1096)
-FUNC(1097)
-FUNC(1098)
-FUNC(1099)
-FUNC(1100)
-FUNC(1101)
-FUNC(1102)
-FUNC(1103)
-FUNC(1104)
-FUNC(1105)
-FUNC(1106)
-FUNC(1107)
-FUNC(1108)
-FUNC(1109)
-FUNC(1110)
-FUNC(1111)
-FUNC(1112)
-FUNC(1113)
-FUNC(1114)
-FUNC(1115)
-FUNC(1116)
-FUNC(1117)
-FUNC(1118)
-FUNC(1119)
-FUNC(1120)
-FUNC(1121)
-FUNC(1122)
-FUNC(1123)
-FUNC(1124)
-FUNC(1125)
-FUNC(1126)
-FUNC(1127)
-FUNC(1128)
-FUNC(1129)
-FUNC(1130)
-FUNC(1131)
-FUNC(1132)
-FUNC(1133)
-FUNC(1134)
-FUNC(1135)
-FUNC(1136)
-FUNC(1137)
-FUNC(1138)
-FUNC(1139)
-FUNC(1140)
-FUNC(1141)
-FUNC(1142)
-FUNC(1143)
-FUNC(1144)
-FUNC(1145)
-FUNC(1146)
-FUNC(1147)
-FUNC(1148)
-FUNC(1149)
-FUNC(1150)
-FUNC(1151)
-FUNC(1152)
-FUNC(1153)
-FUNC(1154)
-FUNC(1155)
-FUNC(1156)
-FUNC(1157)
-FUNC(1158)
-FUNC(1159)
-FUNC(1160)
-FUNC(1161)
-FUNC(1162)
-FUNC(1163)
-FUNC(1164)
-FUNC(1165)
-FUNC(1166)
-FUNC(1167)
-FUNC(1168)
-FUNC(1169)
-FUNC(1170)
-FUNC(1171)
-FUNC(1172)
-FUNC(1173)
-FUNC(1174)
-FUNC(1175)
-FUNC(1176)
-FUNC(1177)
-FUNC(1178)
-FUNC(1179)
-FUNC(1180)
-FUNC(1181)
-FUNC(1182)
-FUNC(1183)
-FUNC(1184)
-FUNC(1185)
-FUNC(1186)
-FUNC(1187)
-FUNC(1188)
-FUNC(1189)
-FUNC(1190)
-FUNC(1191)
-FUNC(1192)
-FUNC(1193)
-FUNC(1194)
-FUNC(1195)
-FUNC(1196)
-FUNC(1197)
-FUNC(1198)
-FUNC(1199)
-FUNC(1200)
-FUNC(1201)
-FUNC(1202)
-FUNC(1203)
-FUNC(1204)
-FUNC(1205)
-FUNC(1206)
-FUNC(1207)
-FUNC(1208)
-FUNC(1209)
-FUNC(1210)
-FUNC(1211)
-FUNC(1212)
-FUNC(1213)
-FUNC(1214)
-FUNC(1215)
-FUNC(1216)
-FUNC(1217)
-FUNC(1218)
-FUNC(1219)
-FUNC(1220)
-FUNC(1221)
-FUNC(1222)
-FUNC(1223)
-FUNC(1224)
-FUNC(1225)
-FUNC(1226)
-FUNC(1227)
-FUNC(1228)
-FUNC(1229)
-FUNC(1230)
-FUNC(1231)
-FUNC(1232)
-FUNC(1233)
-FUNC(1234)
-FUNC(1235)
-FUNC(1236)
-FUNC(1237)
-FUNC(1238)
-FUNC(1239)
-FUNC(1240)
-FUNC(1241)
-FUNC(1242)
-FUNC(1243)
-FUNC(1244)
-FUNC(1245)
-FUNC(1246)
-FUNC(1247)
-FUNC(1248)
-FUNC(1249)
-FUNC(1250)
-FUNC(1251)
-FUNC(1252)
-FUNC(1253)
-FUNC(1254)
-FUNC(1255)
-FUNC(1256)
-FUNC(1257)
-FUNC(1258)
-FUNC(1259)
-FUNC(1260)
-FUNC(1261)
-FUNC(1262)
-FUNC(1263)
-FUNC(1264)
-FUNC(1265)
-FUNC(1266)
-FUNC(1267)
-FUNC(1268)
-FUNC(1269)
-FUNC(1270)
-FUNC(1271)
-FUNC(1272)
-FUNC(1273)
-FUNC(1274)
-FUNC(1275)
-FUNC(1276)
-FUNC(1277)
-FUNC(1278)
-FUNC(1279)
-FUNC(1280)
-FUNC(1281)
-FUNC(1282)
-FUNC(1283)
-FUNC(1284)
-FUNC(1285)
-FUNC(1286)
-FUNC(1287)
-FUNC(1288)
-FUNC(1289)
-FUNC(1290)
-FUNC(1291)
-FUNC(1292)
-FUNC(1293)
-FUNC(1294)
-FUNC(1295)
-FUNC(1296)
-FUNC(1297)
-FUNC(1298)
-FUNC(1299)
-FUNC(1300)
-FUNC(1301)
-FUNC(1302)
-FUNC(1303)
-FUNC(1304)
-FUNC(1305)
-FUNC(1306)
-FUNC(1307)
-FUNC(1308)
-FUNC(1309)
-FUNC(1310)
-FUNC(1311)
-FUNC(1312)
-FUNC(1313)
-FUNC(1314)
-FUNC(1315)
-FUNC(1316)
-FUNC(1317)
-FUNC(1318)
-FUNC(1319)
-FUNC(1320)
-FUNC(1321)
-FUNC(1322)
-FUNC(1323)
-FUNC(1324)
-FUNC(1325)
-FUNC(1326)
-FUNC(1327)
-FUNC(1328)
-FUNC(1329)
-FUNC(1330)
-FUNC(1331)
-FUNC(1332)
-FUNC(1333)
-FUNC(1334)
-FUNC(1335)
-FUNC(1336)
-FUNC(1337)
-FUNC(1338)
-FUNC(1339)
-FUNC(1340)
-FUNC(1341)
-FUNC(1342)
-FUNC(1343)
-FUNC(1344)
-FUNC(1345)
-FUNC(1346)
-FUNC(1347)
-FUNC(1348)
-FUNC(1349)
-FUNC(1350)
-FUNC(1351)
-FUNC(1352)
-FUNC(1353)
-FUNC(1354)
-FUNC(1355)
-FUNC(1356)
-FUNC(1357)
-FUNC(1358)
-FUNC(1359)
-FUNC(1360)
-FUNC(1361)
-FUNC(1362)
-FUNC(1363)
-FUNC(1364)
-FUNC(1365)
-FUNC(1366)
-FUNC(1367)
-FUNC(1368)
-FUNC(1369)
-FUNC(1370)
-FUNC(1371)
-FUNC(1372)
-FUNC(1373)
-FUNC(1374)
-FUNC(1375)
-FUNC(1376)
-FUNC(1377)
-FUNC(1378)
-FUNC(1379)
-FUNC(1380)
-FUNC(1381)
-FUNC(1382)
-FUNC(1383)
-FUNC(1384)
-FUNC(1385)
-FUNC(1386)
-FUNC(1387)
-FUNC(1388)
-FUNC(1389)
-FUNC(1390)
-FUNC(1391)
-FUNC(1392)
-FUNC(1393)
-FUNC(1394)
-FUNC(1395)
-FUNC(1396)
-FUNC(1397)
-FUNC(1398)
-FUNC(1399)
-FUNC(1400)
-FUNC(1401)
-FUNC(1402)
-FUNC(1403)
-FUNC(1404)
-FUNC(1405)
-FUNC(1406)
-FUNC(1407)
-FUNC(1408)
-FUNC(1409)
-FUNC(1410)
-FUNC(1411)
-FUNC(1412)
-FUNC(1413)
-FUNC(1414)
-FUNC(1415)
-FUNC(1416)
-FUNC(1417)
-FUNC(1418)
-FUNC(1419)
-FUNC(1420)
-FUNC(1421)
-FUNC(1422)
-FUNC(1423)
-FUNC(1424)
-FUNC(1425)
-FUNC(1426)
-FUNC(1427)
-FUNC(1428)
-FUNC(1429)
-FUNC(1430)
-FUNC(1431)
-FUNC(1432)
-FUNC(1433)
-FUNC(1434)
-FUNC(1435)
-FUNC(1436)
-FUNC(1437)
-FUNC(1438)
-FUNC(1439)
-FUNC(1440)
-FUNC(1441)
-FUNC(1442)
-FUNC(1443)
-FUNC(1444)
-FUNC(1445)
-FUNC(1446)
-FUNC(1447)
-FUNC(1448)
-FUNC(1449)
-FUNC(1450)
-FUNC(1451)
-FUNC(1452)
-FUNC(1453)
-FUNC(1454)
-FUNC(1455)
-FUNC(1456)
-FUNC(1457)
-FUNC(1458)
-FUNC(1459)
-FUNC(1460)
-FUNC(1461)
-FUNC(1462)
-FUNC(1463)
-FUNC(1464)
-FUNC(1465)
-FUNC(1466)
-FUNC(1467)
-FUNC(1468)
-FUNC(1469)
-FUNC(1470)
-FUNC(1471)
-FUNC(1472)
-FUNC(1473)
-FUNC(1474)
-FUNC(1475)
-FUNC(1476)
-FUNC(1477)
-FUNC(1478)
-FUNC(1479)
-FUNC(1480)
-FUNC(1481)
-FUNC(1482)
-FUNC(1483)
-FUNC(1484)
-FUNC(1485)
-FUNC(1486)
-FUNC(1487)
-FUNC(1488)
-FUNC(1489)
-FUNC(1490)
-FUNC(1491)
-FUNC(1492)
-FUNC(1493)
-FUNC(1494)
-FUNC(1495)
-FUNC(1496)
-FUNC(1497)
-FUNC(1498)
-FUNC(1499)
-FUNC(1500)
-FUNC(1501)
-FUNC(1502)
-FUNC(1503)
-FUNC(1504)
-FUNC(1505)
-FUNC(1506)
-FUNC(1507)
-FUNC(1508)
-FUNC(1509)
-FUNC(1510)
-FUNC(1511)
-FUNC(1512)
-FUNC(1513)
-FUNC(1514)
-FUNC(1515)
-FUNC(1516)
-FUNC(1517)
-FUNC(1518)
-FUNC(1519)
-FUNC(1520)
-FUNC(1521)
-FUNC(1522)
-FUNC(1523)
-FUNC(1524)
-FUNC(1525)
-FUNC(1526)
-FUNC(1527)
-FUNC(1528)
-FUNC(1529)
-FUNC(1530)
-FUNC(1531)
-FUNC(1532)
-FUNC(1533)
-FUNC(1534)
-FUNC(1535)
-FUNC(1536)
-FUNC(1537)
-FUNC(1538)
-FUNC(1539)
-FUNC(1540)
-FUNC(1541)
-FUNC(1542)
-FUNC(1543)
-FUNC(1544)
-FUNC(1545)
-FUNC(1546)
-FUNC(1547)
-FUNC(1548)
-FUNC(1549)
-FUNC(1550)
-FUNC(1551)
-FUNC(1552)
-FUNC(1553)
-FUNC(1554)
-FUNC(1555)
-FUNC(1556)
-FUNC(1557)
-FUNC(1558)
-FUNC(1559)
-FUNC(1560)
-FUNC(1561)
-FUNC(1562)
-FUNC(1563)
-FUNC(1564)
-FUNC(1565)
-FUNC(1566)
-FUNC(1567)
-FUNC(1568)
-FUNC(1569)
-FUNC(1570)
-FUNC(1571)
-FUNC(1572)
-FUNC(1573)
-FUNC(1574)
-FUNC(1575)
-FUNC(1576)
-FUNC(1577)
-FUNC(1578)
-FUNC(1579)
-FUNC(1580)
-FUNC(1581)
-FUNC(1582)
-FUNC(1583)
-FUNC(1584)
-FUNC(1585)
-FUNC(1586)
-FUNC(1587)
-FUNC(1588)
-FUNC(1589)
-FUNC(1590)
-FUNC(1591)
-FUNC(1592)
-FUNC(1593)
-FUNC(1594)
-FUNC(1595)
-FUNC(1596)
-FUNC(1597)
-FUNC(1598)
-FUNC(1599)
-FUNC(1600)
-FUNC(1601)
-FUNC(1602)
-FUNC(1603)
-FUNC(1604)
-FUNC(1605)
-FUNC(1606)
-FUNC(1607)
-FUNC(1608)
-FUNC(1609)
-FUNC(1610)
-FUNC(1611)
-FUNC(1612)
-FUNC(1613)
-FUNC(1614)
-FUNC(1615)
-FUNC(1616)
-FUNC(1617)
-FUNC(1618)
-FUNC(1619)
-FUNC(1620)
-FUNC(1621)
-FUNC(1622)
-FUNC(1623)
-FUNC(1624)
-FUNC(1625)
-FUNC(1626)
-FUNC(1627)
-FUNC(1628)
-FUNC(1629)
-FUNC(1630)
-FUNC(1631)
-FUNC(1632)
-FUNC(1633)
-FUNC(1634)
-FUNC(1635)
-FUNC(1636)
-FUNC(1637)
-FUNC(1638)
-FUNC(1639)
-FUNC(1640)
-FUNC(1641)
-FUNC(1642)
-FUNC(1643)
-FUNC(1644)
-FUNC(1645)
-FUNC(1646)
-FUNC(1647)
-FUNC(1648)
-FUNC(1649)
-FUNC(1650)
-FUNC(1651)
-FUNC(1652)
-FUNC(1653)
-FUNC(1654)
-FUNC(1655)
-FUNC(1656)
-FUNC(1657)
-FUNC(1658)
-FUNC(1659)
-FUNC(1660)
-FUNC(1661)
-FUNC(1662)
-FUNC(1663)
-FUNC(1664)
-FUNC(1665)
-FUNC(1666)
-FUNC(1667)
-FUNC(1668)
-FUNC(1669)
-FUNC(1670)
-FUNC(1671)
-FUNC(1672)
-FUNC(1673)
-FUNC(1674)
-FUNC(1675)
-FUNC(1676)
-FUNC(1677)
-FUNC(1678)
-FUNC(1679)
-FUNC(1680)
-FUNC(1681)
-FUNC(1682)
-FUNC(1683)
-FUNC(1684)
-FUNC(1685)
-FUNC(1686)
-FUNC(1687)
-FUNC(1688)
-FUNC(1689)
-FUNC(1690)
-FUNC(1691)
-FUNC(1692)
-FUNC(1693)
-FUNC(1694)
-FUNC(1695)
-FUNC(1696)
-FUNC(1697)
-FUNC(1698)
-FUNC(1699)
-FUNC(1700)
-FUNC(1701)
-FUNC(1702)
-FUNC(1703)
-FUNC(1704)
-FUNC(1705)
-FUNC(1706)
-FUNC(1707)
-FUNC(1708)
-FUNC(1709)
-FUNC(1710)
-FUNC(1711)
-FUNC(1712)
-FUNC(1713)
-FUNC(1714)
-FUNC(1715)
-FUNC(1716)
-FUNC(1717)
-FUNC(1718)
-FUNC(1719)
-FUNC(1720)
-FUNC(1721)
-FUNC(1722)
-FUNC(1723)
-FUNC(1724)
-FUNC(1725)
-FUNC(1726)
-FUNC(1727)
-FUNC(1728)
-FUNC(1729)
-FUNC(1730)
-FUNC(1731)
-FUNC(1732)
-FUNC(1733)
-FUNC(1734)
-FUNC(1735)
-FUNC(1736)
-FUNC(1737)
-FUNC(1738)
-FUNC(1739)
-FUNC(1740)
-FUNC(1741)
-FUNC(1742)
-FUNC(1743)
-FUNC(1744)
-FUNC(1745)
-FUNC(1746)
-FUNC(1747)
-FUNC(1748)
-FUNC(1749)
-FUNC(1750)
-FUNC(1751)
-FUNC(1752)
-FUNC(1753)
-FUNC(1754)
-FUNC(1755)
-FUNC(1756)
-FUNC(1757)
-FUNC(1758)
-FUNC(1759)
-FUNC(1760)
-FUNC(1761)
-FUNC(1762)
-FUNC(1763)
-FUNC(1764)
-FUNC(1765)
-FUNC(1766)
-FUNC(1767)
-FUNC(1768)
-FUNC(1769)
-FUNC(1770)
-FUNC(1771)
-FUNC(1772)
-FUNC(1773)
-FUNC(1774)
-FUNC(1775)
-FUNC(1776)
-FUNC(1777)
-FUNC(1778)
-FUNC(1779)
-FUNC(1780)
-FUNC(1781)
-FUNC(1782)
-FUNC(1783)
-FUNC(1784)
-FUNC(1785)
-FUNC(1786)
-FUNC(1787)
-FUNC(1788)
-FUNC(1789)
-FUNC(1790)
-FUNC(1791)
-FUNC(1792)
-FUNC(1793)
-FUNC(1794)
-FUNC(1795)
-FUNC(1796)
-FUNC(1797)
-FUNC(1798)
-FUNC(1799)
-FUNC(1800)
-FUNC(1801)
-FUNC(1802)
-FUNC(1803)
-FUNC(1804)
-FUNC(1805)
-FUNC(1806)
-FUNC(1807)
-FUNC(1808)
-FUNC(1809)
-FUNC(1810)
-FUNC(1811)
-FUNC(1812)
-FUNC(1813)
-FUNC(1814)
-FUNC(1815)
-FUNC(1816)
-FUNC(1817)
-FUNC(1818)
-FUNC(1819)
-FUNC(1820)
-FUNC(1821)
-FUNC(1822)
-FUNC(1823)
-FUNC(1824)
-FUNC(1825)
-FUNC(1826)
-FUNC(1827)
-FUNC(1828)
-FUNC(1829)
-FUNC(1830)
-FUNC(1831)
-FUNC(1832)
-FUNC(1833)
-FUNC(1834)
-FUNC(1835)
-FUNC(1836)
-FUNC(1837)
-FUNC(1838)
-FUNC(1839)
-FUNC(1840)
-FUNC(1841)
-FUNC(1842)
-FUNC(1843)
-FUNC(1844)
-FUNC(1845)
-FUNC(1846)
-FUNC(1847)
-FUNC(1848)
-FUNC(1849)
-FUNC(1850)
-FUNC(1851)
-FUNC(1852)
-FUNC(1853)
-FUNC(1854)
-FUNC(1855)
-FUNC(1856)
-FUNC(1857)
-FUNC(1858)
-FUNC(1859)
-FUNC(1860)
-FUNC(1861)
-FUNC(1862)
-FUNC(1863)
-FUNC(1864)
-FUNC(1865)
-FUNC(1866)
-FUNC(1867)
-FUNC(1868)
-FUNC(1869)
-FUNC(1870)
-FUNC(1871)
-FUNC(1872)
-FUNC(1873)
-FUNC(1874)
-FUNC(1875)
-FUNC(1876)
-FUNC(1877)
-FUNC(1878)
-FUNC(1879)
-FUNC(1880)
-FUNC(1881)
-FUNC(1882)
-FUNC(1883)
-FUNC(1884)
-FUNC(1885)
-FUNC(1886)
-FUNC(1887)
-FUNC(1888)
-FUNC(1889)
-FUNC(1890)
-FUNC(1891)
-FUNC(1892)
-FUNC(1893)
-FUNC(1894)
-FUNC(1895)
-FUNC(1896)
-FUNC(1897)
-FUNC(1898)
-FUNC(1899)
-FUNC(1900)
-FUNC(1901)
-FUNC(1902)
-FUNC(1903)
-FUNC(1904)
-FUNC(1905)
-FUNC(1906)
-FUNC(1907)
-FUNC(1908)
-FUNC(1909)
-FUNC(1910)
-FUNC(1911)
-FUNC(1912)
-FUNC(1913)
-FUNC(1914)
-FUNC(1915)
-FUNC(1916)
-FUNC(1917)
-FUNC(1918)
-FUNC(1919)
-FUNC(1920)
-FUNC(1921)
-FUNC(1922)
-FUNC(1923)
-FUNC(1924)
-FUNC(1925)
-FUNC(1926)
-FUNC(1927)
-FUNC(1928)
-FUNC(1929)
-FUNC(1930)
-FUNC(1931)
-FUNC(1932)
-FUNC(1933)
-FUNC(1934)
-FUNC(1935)
-FUNC(1936)
-FUNC(1937)
-FUNC(1938)
-FUNC(1939)
-FUNC(1940)
-FUNC(1941)
-FUNC(1942)
-FUNC(1943)
-FUNC(1944)
-FUNC(1945)
-FUNC(1946)
-FUNC(1947)
-FUNC(1948)
-FUNC(1949)
-FUNC(1950)
-FUNC(1951)
-FUNC(1952)
-FUNC(1953)
-FUNC(1954)
-FUNC(1955)
-FUNC(1956)
-FUNC(1957)
-FUNC(1958)
-FUNC(1959)
-FUNC(1960)
-FUNC(1961)
-FUNC(1962)
-FUNC(1963)
-FUNC(1964)
-FUNC(1965)
-FUNC(1966)
-FUNC(1967)
-FUNC(1968)
-FUNC(1969)
-FUNC(1970)
-FUNC(1971)
-FUNC(1972)
-FUNC(1973)
-FUNC(1974)
-FUNC(1975)
-FUNC(1976)
-FUNC(1977)
-FUNC(1978)
-FUNC(1979)
-FUNC(1980)
-FUNC(1981)
-FUNC(1982)
-FUNC(1983)
-FUNC(1984)
-FUNC(1985)
-FUNC(1986)
-FUNC(1987)
-FUNC(1988)
-FUNC(1989)
-FUNC(1990)
-FUNC(1991)
-FUNC(1992)
-FUNC(1993)
-FUNC(1994)
-FUNC(1995)
-FUNC(1996)
-FUNC(1997)
-FUNC(1998)
-FUNC(1999)
-FUNC(2000)
+/*
+* 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: 
+*
+*/
+/* 
+This is jsut some "compiler fibre" for the compiler to chew
+on as part of a compilation performace test
+*/
+
+#define FUNC(VARIABLE)	\
+int function_##VARIABLE(void)	\
+{	\
+	int x,y,z;	\
+	x=VARIABLE+30* 10-1;	\
+	y=x*4;	\
+	\
+	\
+	x=y+1;	\
+	\
+	int a[VARIABLE];	\
+	\
+	\
+	\
+	for (z=0; z < 1000+VARIABLE; z++)	\
+	{	\
+		x+=a[z];		\
+	}	\
+	\
+	return x;	\
+}
+
+
+
+FUNC(1)
+FUNC(2)
+FUNC(3)
+FUNC(4)
+FUNC(5)
+FUNC(6)
+FUNC(7)
+FUNC(8)
+FUNC(9)
+FUNC(10)
+FUNC(11)
+FUNC(12)
+FUNC(13)
+FUNC(14)
+FUNC(15)
+FUNC(16)
+FUNC(17)
+FUNC(18)
+FUNC(19)
+FUNC(20)
+FUNC(21)
+FUNC(22)
+FUNC(23)
+FUNC(24)
+FUNC(25)
+FUNC(26)
+FUNC(27)
+FUNC(28)
+FUNC(29)
+FUNC(30)
+FUNC(31)
+FUNC(32)
+FUNC(33)
+FUNC(34)
+FUNC(35)
+FUNC(36)
+FUNC(37)
+FUNC(38)
+FUNC(39)
+FUNC(40)
+FUNC(41)
+FUNC(42)
+FUNC(43)
+FUNC(44)
+FUNC(45)
+FUNC(46)
+FUNC(47)
+FUNC(48)
+FUNC(49)
+FUNC(50)
+FUNC(51)
+FUNC(52)
+FUNC(53)
+FUNC(54)
+FUNC(55)
+FUNC(56)
+FUNC(57)
+FUNC(58)
+FUNC(59)
+FUNC(60)
+FUNC(61)
+FUNC(62)
+FUNC(63)
+FUNC(64)
+FUNC(65)
+FUNC(66)
+FUNC(67)
+FUNC(68)
+FUNC(69)
+FUNC(70)
+FUNC(71)
+FUNC(72)
+FUNC(73)
+FUNC(74)
+FUNC(75)
+FUNC(76)
+FUNC(77)
+FUNC(78)
+FUNC(79)
+FUNC(80)
+FUNC(81)
+FUNC(82)
+FUNC(83)
+FUNC(84)
+FUNC(85)
+FUNC(86)
+FUNC(87)
+FUNC(88)
+FUNC(89)
+FUNC(90)
+FUNC(91)
+FUNC(92)
+FUNC(93)
+FUNC(94)
+FUNC(95)
+FUNC(96)
+FUNC(97)
+FUNC(98)
+FUNC(99)
+FUNC(100)
+FUNC(101)
+FUNC(102)
+FUNC(103)
+FUNC(104)
+FUNC(105)
+FUNC(106)
+FUNC(107)
+FUNC(108)
+FUNC(109)
+FUNC(110)
+FUNC(111)
+FUNC(112)
+FUNC(113)
+FUNC(114)
+FUNC(115)
+FUNC(116)
+FUNC(117)
+FUNC(118)
+FUNC(119)
+FUNC(120)
+FUNC(121)
+FUNC(122)
+FUNC(123)
+FUNC(124)
+FUNC(125)
+FUNC(126)
+FUNC(127)
+FUNC(128)
+FUNC(129)
+FUNC(130)
+FUNC(131)
+FUNC(132)
+FUNC(133)
+FUNC(134)
+FUNC(135)
+FUNC(136)
+FUNC(137)
+FUNC(138)
+FUNC(139)
+FUNC(140)
+FUNC(141)
+FUNC(142)
+FUNC(143)
+FUNC(144)
+FUNC(145)
+FUNC(146)
+FUNC(147)
+FUNC(148)
+FUNC(149)
+FUNC(150)
+FUNC(151)
+FUNC(152)
+FUNC(153)
+FUNC(154)
+FUNC(155)
+FUNC(156)
+FUNC(157)
+FUNC(158)
+FUNC(159)
+FUNC(160)
+FUNC(161)
+FUNC(162)
+FUNC(163)
+FUNC(164)
+FUNC(165)
+FUNC(166)
+FUNC(167)
+FUNC(168)
+FUNC(169)
+FUNC(170)
+FUNC(171)
+FUNC(172)
+FUNC(173)
+FUNC(174)
+FUNC(175)
+FUNC(176)
+FUNC(177)
+FUNC(178)
+FUNC(179)
+FUNC(180)
+FUNC(181)
+FUNC(182)
+FUNC(183)
+FUNC(184)
+FUNC(185)
+FUNC(186)
+FUNC(187)
+FUNC(188)
+FUNC(189)
+FUNC(190)
+FUNC(191)
+FUNC(192)
+FUNC(193)
+FUNC(194)
+FUNC(195)
+FUNC(196)
+FUNC(197)
+FUNC(198)
+FUNC(199)
+FUNC(200)
+FUNC(201)
+FUNC(202)
+FUNC(203)
+FUNC(204)
+FUNC(205)
+FUNC(206)
+FUNC(207)
+FUNC(208)
+FUNC(209)
+FUNC(210)
+FUNC(211)
+FUNC(212)
+FUNC(213)
+FUNC(214)
+FUNC(215)
+FUNC(216)
+FUNC(217)
+FUNC(218)
+FUNC(219)
+FUNC(220)
+FUNC(221)
+FUNC(222)
+FUNC(223)
+FUNC(224)
+FUNC(225)
+FUNC(226)
+FUNC(227)
+FUNC(228)
+FUNC(229)
+FUNC(230)
+FUNC(231)
+FUNC(232)
+FUNC(233)
+FUNC(234)
+FUNC(235)
+FUNC(236)
+FUNC(237)
+FUNC(238)
+FUNC(239)
+FUNC(240)
+FUNC(241)
+FUNC(242)
+FUNC(243)
+FUNC(244)
+FUNC(245)
+FUNC(246)
+FUNC(247)
+FUNC(248)
+FUNC(249)
+FUNC(250)
+FUNC(251)
+FUNC(252)
+FUNC(253)
+FUNC(254)
+FUNC(255)
+FUNC(256)
+FUNC(257)
+FUNC(258)
+FUNC(259)
+FUNC(260)
+FUNC(261)
+FUNC(262)
+FUNC(263)
+FUNC(264)
+FUNC(265)
+FUNC(266)
+FUNC(267)
+FUNC(268)
+FUNC(269)
+FUNC(270)
+FUNC(271)
+FUNC(272)
+FUNC(273)
+FUNC(274)
+FUNC(275)
+FUNC(276)
+FUNC(277)
+FUNC(278)
+FUNC(279)
+FUNC(280)
+FUNC(281)
+FUNC(282)
+FUNC(283)
+FUNC(284)
+FUNC(285)
+FUNC(286)
+FUNC(287)
+FUNC(288)
+FUNC(289)
+FUNC(290)
+FUNC(291)
+FUNC(292)
+FUNC(293)
+FUNC(294)
+FUNC(295)
+FUNC(296)
+FUNC(297)
+FUNC(298)
+FUNC(299)
+FUNC(300)
+FUNC(301)
+FUNC(302)
+FUNC(303)
+FUNC(304)
+FUNC(305)
+FUNC(306)
+FUNC(307)
+FUNC(308)
+FUNC(309)
+FUNC(310)
+FUNC(311)
+FUNC(312)
+FUNC(313)
+FUNC(314)
+FUNC(315)
+FUNC(316)
+FUNC(317)
+FUNC(318)
+FUNC(319)
+FUNC(320)
+FUNC(321)
+FUNC(322)
+FUNC(323)
+FUNC(324)
+FUNC(325)
+FUNC(326)
+FUNC(327)
+FUNC(328)
+FUNC(329)
+FUNC(330)
+FUNC(331)
+FUNC(332)
+FUNC(333)
+FUNC(334)
+FUNC(335)
+FUNC(336)
+FUNC(337)
+FUNC(338)
+FUNC(339)
+FUNC(340)
+FUNC(341)
+FUNC(342)
+FUNC(343)
+FUNC(344)
+FUNC(345)
+FUNC(346)
+FUNC(347)
+FUNC(348)
+FUNC(349)
+FUNC(350)
+FUNC(351)
+FUNC(352)
+FUNC(353)
+FUNC(354)
+FUNC(355)
+FUNC(356)
+FUNC(357)
+FUNC(358)
+FUNC(359)
+FUNC(360)
+FUNC(361)
+FUNC(362)
+FUNC(363)
+FUNC(364)
+FUNC(365)
+FUNC(366)
+FUNC(367)
+FUNC(368)
+FUNC(369)
+FUNC(370)
+FUNC(371)
+FUNC(372)
+FUNC(373)
+FUNC(374)
+FUNC(375)
+FUNC(376)
+FUNC(377)
+FUNC(378)
+FUNC(379)
+FUNC(380)
+FUNC(381)
+FUNC(382)
+FUNC(383)
+FUNC(384)
+FUNC(385)
+FUNC(386)
+FUNC(387)
+FUNC(388)
+FUNC(389)
+FUNC(390)
+FUNC(391)
+FUNC(392)
+FUNC(393)
+FUNC(394)
+FUNC(395)
+FUNC(396)
+FUNC(397)
+FUNC(398)
+FUNC(399)
+FUNC(400)
+FUNC(401)
+FUNC(402)
+FUNC(403)
+FUNC(404)
+FUNC(405)
+FUNC(406)
+FUNC(407)
+FUNC(408)
+FUNC(409)
+FUNC(410)
+FUNC(411)
+FUNC(412)
+FUNC(413)
+FUNC(414)
+FUNC(415)
+FUNC(416)
+FUNC(417)
+FUNC(418)
+FUNC(419)
+FUNC(420)
+FUNC(421)
+FUNC(422)
+FUNC(423)
+FUNC(424)
+FUNC(425)
+FUNC(426)
+FUNC(427)
+FUNC(428)
+FUNC(429)
+FUNC(430)
+FUNC(431)
+FUNC(432)
+FUNC(433)
+FUNC(434)
+FUNC(435)
+FUNC(436)
+FUNC(437)
+FUNC(438)
+FUNC(439)
+FUNC(440)
+FUNC(441)
+FUNC(442)
+FUNC(443)
+FUNC(444)
+FUNC(445)
+FUNC(446)
+FUNC(447)
+FUNC(448)
+FUNC(449)
+FUNC(450)
+FUNC(451)
+FUNC(452)
+FUNC(453)
+FUNC(454)
+FUNC(455)
+FUNC(456)
+FUNC(457)
+FUNC(458)
+FUNC(459)
+FUNC(460)
+FUNC(461)
+FUNC(462)
+FUNC(463)
+FUNC(464)
+FUNC(465)
+FUNC(466)
+FUNC(467)
+FUNC(468)
+FUNC(469)
+FUNC(470)
+FUNC(471)
+FUNC(472)
+FUNC(473)
+FUNC(474)
+FUNC(475)
+FUNC(476)
+FUNC(477)
+FUNC(478)
+FUNC(479)
+FUNC(480)
+FUNC(481)
+FUNC(482)
+FUNC(483)
+FUNC(484)
+FUNC(485)
+FUNC(486)
+FUNC(487)
+FUNC(488)
+FUNC(489)
+FUNC(490)
+FUNC(491)
+FUNC(492)
+FUNC(493)
+FUNC(494)
+FUNC(495)
+FUNC(496)
+FUNC(497)
+FUNC(498)
+FUNC(499)
+FUNC(500)
+FUNC(501)
+FUNC(502)
+FUNC(503)
+FUNC(504)
+FUNC(505)
+FUNC(506)
+FUNC(507)
+FUNC(508)
+FUNC(509)
+FUNC(510)
+FUNC(511)
+FUNC(512)
+FUNC(513)
+FUNC(514)
+FUNC(515)
+FUNC(516)
+FUNC(517)
+FUNC(518)
+FUNC(519)
+FUNC(520)
+FUNC(521)
+FUNC(522)
+FUNC(523)
+FUNC(524)
+FUNC(525)
+FUNC(526)
+FUNC(527)
+FUNC(528)
+FUNC(529)
+FUNC(530)
+FUNC(531)
+FUNC(532)
+FUNC(533)
+FUNC(534)
+FUNC(535)
+FUNC(536)
+FUNC(537)
+FUNC(538)
+FUNC(539)
+FUNC(540)
+FUNC(541)
+FUNC(542)
+FUNC(543)
+FUNC(544)
+FUNC(545)
+FUNC(546)
+FUNC(547)
+FUNC(548)
+FUNC(549)
+FUNC(550)
+FUNC(551)
+FUNC(552)
+FUNC(553)
+FUNC(554)
+FUNC(555)
+FUNC(556)
+FUNC(557)
+FUNC(558)
+FUNC(559)
+FUNC(560)
+FUNC(561)
+FUNC(562)
+FUNC(563)
+FUNC(564)
+FUNC(565)
+FUNC(566)
+FUNC(567)
+FUNC(568)
+FUNC(569)
+FUNC(570)
+FUNC(571)
+FUNC(572)
+FUNC(573)
+FUNC(574)
+FUNC(575)
+FUNC(576)
+FUNC(577)
+FUNC(578)
+FUNC(579)
+FUNC(580)
+FUNC(581)
+FUNC(582)
+FUNC(583)
+FUNC(584)
+FUNC(585)
+FUNC(586)
+FUNC(587)
+FUNC(588)
+FUNC(589)
+FUNC(590)
+FUNC(591)
+FUNC(592)
+FUNC(593)
+FUNC(594)
+FUNC(595)
+FUNC(596)
+FUNC(597)
+FUNC(598)
+FUNC(599)
+FUNC(600)
+FUNC(601)
+FUNC(602)
+FUNC(603)
+FUNC(604)
+FUNC(605)
+FUNC(606)
+FUNC(607)
+FUNC(608)
+FUNC(609)
+FUNC(610)
+FUNC(611)
+FUNC(612)
+FUNC(613)
+FUNC(614)
+FUNC(615)
+FUNC(616)
+FUNC(617)
+FUNC(618)
+FUNC(619)
+FUNC(620)
+FUNC(621)
+FUNC(622)
+FUNC(623)
+FUNC(624)
+FUNC(625)
+FUNC(626)
+FUNC(627)
+FUNC(628)
+FUNC(629)
+FUNC(630)
+FUNC(631)
+FUNC(632)
+FUNC(633)
+FUNC(634)
+FUNC(635)
+FUNC(636)
+FUNC(637)
+FUNC(638)
+FUNC(639)
+FUNC(640)
+FUNC(641)
+FUNC(642)
+FUNC(643)
+FUNC(644)
+FUNC(645)
+FUNC(646)
+FUNC(647)
+FUNC(648)
+FUNC(649)
+FUNC(650)
+FUNC(651)
+FUNC(652)
+FUNC(653)
+FUNC(654)
+FUNC(655)
+FUNC(656)
+FUNC(657)
+FUNC(658)
+FUNC(659)
+FUNC(660)
+FUNC(661)
+FUNC(662)
+FUNC(663)
+FUNC(664)
+FUNC(665)
+FUNC(666)
+FUNC(667)
+FUNC(668)
+FUNC(669)
+FUNC(670)
+FUNC(671)
+FUNC(672)
+FUNC(673)
+FUNC(674)
+FUNC(675)
+FUNC(676)
+FUNC(677)
+FUNC(678)
+FUNC(679)
+FUNC(680)
+FUNC(681)
+FUNC(682)
+FUNC(683)
+FUNC(684)
+FUNC(685)
+FUNC(686)
+FUNC(687)
+FUNC(688)
+FUNC(689)
+FUNC(690)
+FUNC(691)
+FUNC(692)
+FUNC(693)
+FUNC(694)
+FUNC(695)
+FUNC(696)
+FUNC(697)
+FUNC(698)
+FUNC(699)
+FUNC(700)
+FUNC(701)
+FUNC(702)
+FUNC(703)
+FUNC(704)
+FUNC(705)
+FUNC(706)
+FUNC(707)
+FUNC(708)
+FUNC(709)
+FUNC(710)
+FUNC(711)
+FUNC(712)
+FUNC(713)
+FUNC(714)
+FUNC(715)
+FUNC(716)
+FUNC(717)
+FUNC(718)
+FUNC(719)
+FUNC(720)
+FUNC(721)
+FUNC(722)
+FUNC(723)
+FUNC(724)
+FUNC(725)
+FUNC(726)
+FUNC(727)
+FUNC(728)
+FUNC(729)
+FUNC(730)
+FUNC(731)
+FUNC(732)
+FUNC(733)
+FUNC(734)
+FUNC(735)
+FUNC(736)
+FUNC(737)
+FUNC(738)
+FUNC(739)
+FUNC(740)
+FUNC(741)
+FUNC(742)
+FUNC(743)
+FUNC(744)
+FUNC(745)
+FUNC(746)
+FUNC(747)
+FUNC(748)
+FUNC(749)
+FUNC(750)
+FUNC(751)
+FUNC(752)
+FUNC(753)
+FUNC(754)
+FUNC(755)
+FUNC(756)
+FUNC(757)
+FUNC(758)
+FUNC(759)
+FUNC(760)
+FUNC(761)
+FUNC(762)
+FUNC(763)
+FUNC(764)
+FUNC(765)
+FUNC(766)
+FUNC(767)
+FUNC(768)
+FUNC(769)
+FUNC(770)
+FUNC(771)
+FUNC(772)
+FUNC(773)
+FUNC(774)
+FUNC(775)
+FUNC(776)
+FUNC(777)
+FUNC(778)
+FUNC(779)
+FUNC(780)
+FUNC(781)
+FUNC(782)
+FUNC(783)
+FUNC(784)
+FUNC(785)
+FUNC(786)
+FUNC(787)
+FUNC(788)
+FUNC(789)
+FUNC(790)
+FUNC(791)
+FUNC(792)
+FUNC(793)
+FUNC(794)
+FUNC(795)
+FUNC(796)
+FUNC(797)
+FUNC(798)
+FUNC(799)
+FUNC(800)
+FUNC(801)
+FUNC(802)
+FUNC(803)
+FUNC(804)
+FUNC(805)
+FUNC(806)
+FUNC(807)
+FUNC(808)
+FUNC(809)
+FUNC(810)
+FUNC(811)
+FUNC(812)
+FUNC(813)
+FUNC(814)
+FUNC(815)
+FUNC(816)
+FUNC(817)
+FUNC(818)
+FUNC(819)
+FUNC(820)
+FUNC(821)
+FUNC(822)
+FUNC(823)
+FUNC(824)
+FUNC(825)
+FUNC(826)
+FUNC(827)
+FUNC(828)
+FUNC(829)
+FUNC(830)
+FUNC(831)
+FUNC(832)
+FUNC(833)
+FUNC(834)
+FUNC(835)
+FUNC(836)
+FUNC(837)
+FUNC(838)
+FUNC(839)
+FUNC(840)
+FUNC(841)
+FUNC(842)
+FUNC(843)
+FUNC(844)
+FUNC(845)
+FUNC(846)
+FUNC(847)
+FUNC(848)
+FUNC(849)
+FUNC(850)
+FUNC(851)
+FUNC(852)
+FUNC(853)
+FUNC(854)
+FUNC(855)
+FUNC(856)
+FUNC(857)
+FUNC(858)
+FUNC(859)
+FUNC(860)
+FUNC(861)
+FUNC(862)
+FUNC(863)
+FUNC(864)
+FUNC(865)
+FUNC(866)
+FUNC(867)
+FUNC(868)
+FUNC(869)
+FUNC(870)
+FUNC(871)
+FUNC(872)
+FUNC(873)
+FUNC(874)
+FUNC(875)
+FUNC(876)
+FUNC(877)
+FUNC(878)
+FUNC(879)
+FUNC(880)
+FUNC(881)
+FUNC(882)
+FUNC(883)
+FUNC(884)
+FUNC(885)
+FUNC(886)
+FUNC(887)
+FUNC(888)
+FUNC(889)
+FUNC(890)
+FUNC(891)
+FUNC(892)
+FUNC(893)
+FUNC(894)
+FUNC(895)
+FUNC(896)
+FUNC(897)
+FUNC(898)
+FUNC(899)
+FUNC(900)
+FUNC(901)
+FUNC(902)
+FUNC(903)
+FUNC(904)
+FUNC(905)
+FUNC(906)
+FUNC(907)
+FUNC(908)
+FUNC(909)
+FUNC(910)
+FUNC(911)
+FUNC(912)
+FUNC(913)
+FUNC(914)
+FUNC(915)
+FUNC(916)
+FUNC(917)
+FUNC(918)
+FUNC(919)
+FUNC(920)
+FUNC(921)
+FUNC(922)
+FUNC(923)
+FUNC(924)
+FUNC(925)
+FUNC(926)
+FUNC(927)
+FUNC(928)
+FUNC(929)
+FUNC(930)
+FUNC(931)
+FUNC(932)
+FUNC(933)
+FUNC(934)
+FUNC(935)
+FUNC(936)
+FUNC(937)
+FUNC(938)
+FUNC(939)
+FUNC(940)
+FUNC(941)
+FUNC(942)
+FUNC(943)
+FUNC(944)
+FUNC(945)
+FUNC(946)
+FUNC(947)
+FUNC(948)
+FUNC(949)
+FUNC(950)
+FUNC(951)
+FUNC(952)
+FUNC(953)
+FUNC(954)
+FUNC(955)
+FUNC(956)
+FUNC(957)
+FUNC(958)
+FUNC(959)
+FUNC(960)
+FUNC(961)
+FUNC(962)
+FUNC(963)
+FUNC(964)
+FUNC(965)
+FUNC(966)
+FUNC(967)
+FUNC(968)
+FUNC(969)
+FUNC(970)
+FUNC(971)
+FUNC(972)
+FUNC(973)
+FUNC(974)
+FUNC(975)
+FUNC(976)
+FUNC(977)
+FUNC(978)
+FUNC(979)
+FUNC(980)
+FUNC(981)
+FUNC(982)
+FUNC(983)
+FUNC(984)
+FUNC(985)
+FUNC(986)
+FUNC(987)
+FUNC(988)
+FUNC(989)
+FUNC(990)
+FUNC(991)
+FUNC(992)
+FUNC(993)
+FUNC(994)
+FUNC(995)
+FUNC(996)
+FUNC(997)
+FUNC(998)
+FUNC(999)
+FUNC(1000)
+FUNC(1001)
+FUNC(1002)
+FUNC(1003)
+FUNC(1004)
+FUNC(1005)
+FUNC(1006)
+FUNC(1007)
+FUNC(1008)
+FUNC(1009)
+FUNC(1010)
+FUNC(1011)
+FUNC(1012)
+FUNC(1013)
+FUNC(1014)
+FUNC(1015)
+FUNC(1016)
+FUNC(1017)
+FUNC(1018)
+FUNC(1019)
+FUNC(1020)
+FUNC(1021)
+FUNC(1022)
+FUNC(1023)
+FUNC(1024)
+FUNC(1025)
+FUNC(1026)
+FUNC(1027)
+FUNC(1028)
+FUNC(1029)
+FUNC(1030)
+FUNC(1031)
+FUNC(1032)
+FUNC(1033)
+FUNC(1034)
+FUNC(1035)
+FUNC(1036)
+FUNC(1037)
+FUNC(1038)
+FUNC(1039)
+FUNC(1040)
+FUNC(1041)
+FUNC(1042)
+FUNC(1043)
+FUNC(1044)
+FUNC(1045)
+FUNC(1046)
+FUNC(1047)
+FUNC(1048)
+FUNC(1049)
+FUNC(1050)
+FUNC(1051)
+FUNC(1052)
+FUNC(1053)
+FUNC(1054)
+FUNC(1055)
+FUNC(1056)
+FUNC(1057)
+FUNC(1058)
+FUNC(1059)
+FUNC(1060)
+FUNC(1061)
+FUNC(1062)
+FUNC(1063)
+FUNC(1064)
+FUNC(1065)
+FUNC(1066)
+FUNC(1067)
+FUNC(1068)
+FUNC(1069)
+FUNC(1070)
+FUNC(1071)
+FUNC(1072)
+FUNC(1073)
+FUNC(1074)
+FUNC(1075)
+FUNC(1076)
+FUNC(1077)
+FUNC(1078)
+FUNC(1079)
+FUNC(1080)
+FUNC(1081)
+FUNC(1082)
+FUNC(1083)
+FUNC(1084)
+FUNC(1085)
+FUNC(1086)
+FUNC(1087)
+FUNC(1088)
+FUNC(1089)
+FUNC(1090)
+FUNC(1091)
+FUNC(1092)
+FUNC(1093)
+FUNC(1094)
+FUNC(1095)
+FUNC(1096)
+FUNC(1097)
+FUNC(1098)
+FUNC(1099)
+FUNC(1100)
+FUNC(1101)
+FUNC(1102)
+FUNC(1103)
+FUNC(1104)
+FUNC(1105)
+FUNC(1106)
+FUNC(1107)
+FUNC(1108)
+FUNC(1109)
+FUNC(1110)
+FUNC(1111)
+FUNC(1112)
+FUNC(1113)
+FUNC(1114)
+FUNC(1115)
+FUNC(1116)
+FUNC(1117)
+FUNC(1118)
+FUNC(1119)
+FUNC(1120)
+FUNC(1121)
+FUNC(1122)
+FUNC(1123)
+FUNC(1124)
+FUNC(1125)
+FUNC(1126)
+FUNC(1127)
+FUNC(1128)
+FUNC(1129)
+FUNC(1130)
+FUNC(1131)
+FUNC(1132)
+FUNC(1133)
+FUNC(1134)
+FUNC(1135)
+FUNC(1136)
+FUNC(1137)
+FUNC(1138)
+FUNC(1139)
+FUNC(1140)
+FUNC(1141)
+FUNC(1142)
+FUNC(1143)
+FUNC(1144)
+FUNC(1145)
+FUNC(1146)
+FUNC(1147)
+FUNC(1148)
+FUNC(1149)
+FUNC(1150)
+FUNC(1151)
+FUNC(1152)
+FUNC(1153)
+FUNC(1154)
+FUNC(1155)
+FUNC(1156)
+FUNC(1157)
+FUNC(1158)
+FUNC(1159)
+FUNC(1160)
+FUNC(1161)
+FUNC(1162)
+FUNC(1163)
+FUNC(1164)
+FUNC(1165)
+FUNC(1166)
+FUNC(1167)
+FUNC(1168)
+FUNC(1169)
+FUNC(1170)
+FUNC(1171)
+FUNC(1172)
+FUNC(1173)
+FUNC(1174)
+FUNC(1175)
+FUNC(1176)
+FUNC(1177)
+FUNC(1178)
+FUNC(1179)
+FUNC(1180)
+FUNC(1181)
+FUNC(1182)
+FUNC(1183)
+FUNC(1184)
+FUNC(1185)
+FUNC(1186)
+FUNC(1187)
+FUNC(1188)
+FUNC(1189)
+FUNC(1190)
+FUNC(1191)
+FUNC(1192)
+FUNC(1193)
+FUNC(1194)
+FUNC(1195)
+FUNC(1196)
+FUNC(1197)
+FUNC(1198)
+FUNC(1199)
+FUNC(1200)
+FUNC(1201)
+FUNC(1202)
+FUNC(1203)
+FUNC(1204)
+FUNC(1205)
+FUNC(1206)
+FUNC(1207)
+FUNC(1208)
+FUNC(1209)
+FUNC(1210)
+FUNC(1211)
+FUNC(1212)
+FUNC(1213)
+FUNC(1214)
+FUNC(1215)
+FUNC(1216)
+FUNC(1217)
+FUNC(1218)
+FUNC(1219)
+FUNC(1220)
+FUNC(1221)
+FUNC(1222)
+FUNC(1223)
+FUNC(1224)
+FUNC(1225)
+FUNC(1226)
+FUNC(1227)
+FUNC(1228)
+FUNC(1229)
+FUNC(1230)
+FUNC(1231)
+FUNC(1232)
+FUNC(1233)
+FUNC(1234)
+FUNC(1235)
+FUNC(1236)
+FUNC(1237)
+FUNC(1238)
+FUNC(1239)
+FUNC(1240)
+FUNC(1241)
+FUNC(1242)
+FUNC(1243)
+FUNC(1244)
+FUNC(1245)
+FUNC(1246)
+FUNC(1247)
+FUNC(1248)
+FUNC(1249)
+FUNC(1250)
+FUNC(1251)
+FUNC(1252)
+FUNC(1253)
+FUNC(1254)
+FUNC(1255)
+FUNC(1256)
+FUNC(1257)
+FUNC(1258)
+FUNC(1259)
+FUNC(1260)
+FUNC(1261)
+FUNC(1262)
+FUNC(1263)
+FUNC(1264)
+FUNC(1265)
+FUNC(1266)
+FUNC(1267)
+FUNC(1268)
+FUNC(1269)
+FUNC(1270)
+FUNC(1271)
+FUNC(1272)
+FUNC(1273)
+FUNC(1274)
+FUNC(1275)
+FUNC(1276)
+FUNC(1277)
+FUNC(1278)
+FUNC(1279)
+FUNC(1280)
+FUNC(1281)
+FUNC(1282)
+FUNC(1283)
+FUNC(1284)
+FUNC(1285)
+FUNC(1286)
+FUNC(1287)
+FUNC(1288)
+FUNC(1289)
+FUNC(1290)
+FUNC(1291)
+FUNC(1292)
+FUNC(1293)
+FUNC(1294)
+FUNC(1295)
+FUNC(1296)
+FUNC(1297)
+FUNC(1298)
+FUNC(1299)
+FUNC(1300)
+FUNC(1301)
+FUNC(1302)
+FUNC(1303)
+FUNC(1304)
+FUNC(1305)
+FUNC(1306)
+FUNC(1307)
+FUNC(1308)
+FUNC(1309)
+FUNC(1310)
+FUNC(1311)
+FUNC(1312)
+FUNC(1313)
+FUNC(1314)
+FUNC(1315)
+FUNC(1316)
+FUNC(1317)
+FUNC(1318)
+FUNC(1319)
+FUNC(1320)
+FUNC(1321)
+FUNC(1322)
+FUNC(1323)
+FUNC(1324)
+FUNC(1325)
+FUNC(1326)
+FUNC(1327)
+FUNC(1328)
+FUNC(1329)
+FUNC(1330)
+FUNC(1331)
+FUNC(1332)
+FUNC(1333)
+FUNC(1334)
+FUNC(1335)
+FUNC(1336)
+FUNC(1337)
+FUNC(1338)
+FUNC(1339)
+FUNC(1340)
+FUNC(1341)
+FUNC(1342)
+FUNC(1343)
+FUNC(1344)
+FUNC(1345)
+FUNC(1346)
+FUNC(1347)
+FUNC(1348)
+FUNC(1349)
+FUNC(1350)
+FUNC(1351)
+FUNC(1352)
+FUNC(1353)
+FUNC(1354)
+FUNC(1355)
+FUNC(1356)
+FUNC(1357)
+FUNC(1358)
+FUNC(1359)
+FUNC(1360)
+FUNC(1361)
+FUNC(1362)
+FUNC(1363)
+FUNC(1364)
+FUNC(1365)
+FUNC(1366)
+FUNC(1367)
+FUNC(1368)
+FUNC(1369)
+FUNC(1370)
+FUNC(1371)
+FUNC(1372)
+FUNC(1373)
+FUNC(1374)
+FUNC(1375)
+FUNC(1376)
+FUNC(1377)
+FUNC(1378)
+FUNC(1379)
+FUNC(1380)
+FUNC(1381)
+FUNC(1382)
+FUNC(1383)
+FUNC(1384)
+FUNC(1385)
+FUNC(1386)
+FUNC(1387)
+FUNC(1388)
+FUNC(1389)
+FUNC(1390)
+FUNC(1391)
+FUNC(1392)
+FUNC(1393)
+FUNC(1394)
+FUNC(1395)
+FUNC(1396)
+FUNC(1397)
+FUNC(1398)
+FUNC(1399)
+FUNC(1400)
+FUNC(1401)
+FUNC(1402)
+FUNC(1403)
+FUNC(1404)
+FUNC(1405)
+FUNC(1406)
+FUNC(1407)
+FUNC(1408)
+FUNC(1409)
+FUNC(1410)
+FUNC(1411)
+FUNC(1412)
+FUNC(1413)
+FUNC(1414)
+FUNC(1415)
+FUNC(1416)
+FUNC(1417)
+FUNC(1418)
+FUNC(1419)
+FUNC(1420)
+FUNC(1421)
+FUNC(1422)
+FUNC(1423)
+FUNC(1424)
+FUNC(1425)
+FUNC(1426)
+FUNC(1427)
+FUNC(1428)
+FUNC(1429)
+FUNC(1430)
+FUNC(1431)
+FUNC(1432)
+FUNC(1433)
+FUNC(1434)
+FUNC(1435)
+FUNC(1436)
+FUNC(1437)
+FUNC(1438)
+FUNC(1439)
+FUNC(1440)
+FUNC(1441)
+FUNC(1442)
+FUNC(1443)
+FUNC(1444)
+FUNC(1445)
+FUNC(1446)
+FUNC(1447)
+FUNC(1448)
+FUNC(1449)
+FUNC(1450)
+FUNC(1451)
+FUNC(1452)
+FUNC(1453)
+FUNC(1454)
+FUNC(1455)
+FUNC(1456)
+FUNC(1457)
+FUNC(1458)
+FUNC(1459)
+FUNC(1460)
+FUNC(1461)
+FUNC(1462)
+FUNC(1463)
+FUNC(1464)
+FUNC(1465)
+FUNC(1466)
+FUNC(1467)
+FUNC(1468)
+FUNC(1469)
+FUNC(1470)
+FUNC(1471)
+FUNC(1472)
+FUNC(1473)
+FUNC(1474)
+FUNC(1475)
+FUNC(1476)
+FUNC(1477)
+FUNC(1478)
+FUNC(1479)
+FUNC(1480)
+FUNC(1481)
+FUNC(1482)
+FUNC(1483)
+FUNC(1484)
+FUNC(1485)
+FUNC(1486)
+FUNC(1487)
+FUNC(1488)
+FUNC(1489)
+FUNC(1490)
+FUNC(1491)
+FUNC(1492)
+FUNC(1493)
+FUNC(1494)
+FUNC(1495)
+FUNC(1496)
+FUNC(1497)
+FUNC(1498)
+FUNC(1499)
+FUNC(1500)
+FUNC(1501)
+FUNC(1502)
+FUNC(1503)
+FUNC(1504)
+FUNC(1505)
+FUNC(1506)
+FUNC(1507)
+FUNC(1508)
+FUNC(1509)
+FUNC(1510)
+FUNC(1511)
+FUNC(1512)
+FUNC(1513)
+FUNC(1514)
+FUNC(1515)
+FUNC(1516)
+FUNC(1517)
+FUNC(1518)
+FUNC(1519)
+FUNC(1520)
+FUNC(1521)
+FUNC(1522)
+FUNC(1523)
+FUNC(1524)
+FUNC(1525)
+FUNC(1526)
+FUNC(1527)
+FUNC(1528)
+FUNC(1529)
+FUNC(1530)
+FUNC(1531)
+FUNC(1532)
+FUNC(1533)
+FUNC(1534)
+FUNC(1535)
+FUNC(1536)
+FUNC(1537)
+FUNC(1538)
+FUNC(1539)
+FUNC(1540)
+FUNC(1541)
+FUNC(1542)
+FUNC(1543)
+FUNC(1544)
+FUNC(1545)
+FUNC(1546)
+FUNC(1547)
+FUNC(1548)
+FUNC(1549)
+FUNC(1550)
+FUNC(1551)
+FUNC(1552)
+FUNC(1553)
+FUNC(1554)
+FUNC(1555)
+FUNC(1556)
+FUNC(1557)
+FUNC(1558)
+FUNC(1559)
+FUNC(1560)
+FUNC(1561)
+FUNC(1562)
+FUNC(1563)
+FUNC(1564)
+FUNC(1565)
+FUNC(1566)
+FUNC(1567)
+FUNC(1568)
+FUNC(1569)
+FUNC(1570)
+FUNC(1571)
+FUNC(1572)
+FUNC(1573)
+FUNC(1574)
+FUNC(1575)
+FUNC(1576)
+FUNC(1577)
+FUNC(1578)
+FUNC(1579)
+FUNC(1580)
+FUNC(1581)
+FUNC(1582)
+FUNC(1583)
+FUNC(1584)
+FUNC(1585)
+FUNC(1586)
+FUNC(1587)
+FUNC(1588)
+FUNC(1589)
+FUNC(1590)
+FUNC(1591)
+FUNC(1592)
+FUNC(1593)
+FUNC(1594)
+FUNC(1595)
+FUNC(1596)
+FUNC(1597)
+FUNC(1598)
+FUNC(1599)
+FUNC(1600)
+FUNC(1601)
+FUNC(1602)
+FUNC(1603)
+FUNC(1604)
+FUNC(1605)
+FUNC(1606)
+FUNC(1607)
+FUNC(1608)
+FUNC(1609)
+FUNC(1610)
+FUNC(1611)
+FUNC(1612)
+FUNC(1613)
+FUNC(1614)
+FUNC(1615)
+FUNC(1616)
+FUNC(1617)
+FUNC(1618)
+FUNC(1619)
+FUNC(1620)
+FUNC(1621)
+FUNC(1622)
+FUNC(1623)
+FUNC(1624)
+FUNC(1625)
+FUNC(1626)
+FUNC(1627)
+FUNC(1628)
+FUNC(1629)
+FUNC(1630)
+FUNC(1631)
+FUNC(1632)
+FUNC(1633)
+FUNC(1634)
+FUNC(1635)
+FUNC(1636)
+FUNC(1637)
+FUNC(1638)
+FUNC(1639)
+FUNC(1640)
+FUNC(1641)
+FUNC(1642)
+FUNC(1643)
+FUNC(1644)
+FUNC(1645)
+FUNC(1646)
+FUNC(1647)
+FUNC(1648)
+FUNC(1649)
+FUNC(1650)
+FUNC(1651)
+FUNC(1652)
+FUNC(1653)
+FUNC(1654)
+FUNC(1655)
+FUNC(1656)
+FUNC(1657)
+FUNC(1658)
+FUNC(1659)
+FUNC(1660)
+FUNC(1661)
+FUNC(1662)
+FUNC(1663)
+FUNC(1664)
+FUNC(1665)
+FUNC(1666)
+FUNC(1667)
+FUNC(1668)
+FUNC(1669)
+FUNC(1670)
+FUNC(1671)
+FUNC(1672)
+FUNC(1673)
+FUNC(1674)
+FUNC(1675)
+FUNC(1676)
+FUNC(1677)
+FUNC(1678)
+FUNC(1679)
+FUNC(1680)
+FUNC(1681)
+FUNC(1682)
+FUNC(1683)
+FUNC(1684)
+FUNC(1685)
+FUNC(1686)
+FUNC(1687)
+FUNC(1688)
+FUNC(1689)
+FUNC(1690)
+FUNC(1691)
+FUNC(1692)
+FUNC(1693)
+FUNC(1694)
+FUNC(1695)
+FUNC(1696)
+FUNC(1697)
+FUNC(1698)
+FUNC(1699)
+FUNC(1700)
+FUNC(1701)
+FUNC(1702)
+FUNC(1703)
+FUNC(1704)
+FUNC(1705)
+FUNC(1706)
+FUNC(1707)
+FUNC(1708)
+FUNC(1709)
+FUNC(1710)
+FUNC(1711)
+FUNC(1712)
+FUNC(1713)
+FUNC(1714)
+FUNC(1715)
+FUNC(1716)
+FUNC(1717)
+FUNC(1718)
+FUNC(1719)
+FUNC(1720)
+FUNC(1721)
+FUNC(1722)
+FUNC(1723)
+FUNC(1724)
+FUNC(1725)
+FUNC(1726)
+FUNC(1727)
+FUNC(1728)
+FUNC(1729)
+FUNC(1730)
+FUNC(1731)
+FUNC(1732)
+FUNC(1733)
+FUNC(1734)
+FUNC(1735)
+FUNC(1736)
+FUNC(1737)
+FUNC(1738)
+FUNC(1739)
+FUNC(1740)
+FUNC(1741)
+FUNC(1742)
+FUNC(1743)
+FUNC(1744)
+FUNC(1745)
+FUNC(1746)
+FUNC(1747)
+FUNC(1748)
+FUNC(1749)
+FUNC(1750)
+FUNC(1751)
+FUNC(1752)
+FUNC(1753)
+FUNC(1754)
+FUNC(1755)
+FUNC(1756)
+FUNC(1757)
+FUNC(1758)
+FUNC(1759)
+FUNC(1760)
+FUNC(1761)
+FUNC(1762)
+FUNC(1763)
+FUNC(1764)
+FUNC(1765)
+FUNC(1766)
+FUNC(1767)
+FUNC(1768)
+FUNC(1769)
+FUNC(1770)
+FUNC(1771)
+FUNC(1772)
+FUNC(1773)
+FUNC(1774)
+FUNC(1775)
+FUNC(1776)
+FUNC(1777)
+FUNC(1778)
+FUNC(1779)
+FUNC(1780)
+FUNC(1781)
+FUNC(1782)
+FUNC(1783)
+FUNC(1784)
+FUNC(1785)
+FUNC(1786)
+FUNC(1787)
+FUNC(1788)
+FUNC(1789)
+FUNC(1790)
+FUNC(1791)
+FUNC(1792)
+FUNC(1793)
+FUNC(1794)
+FUNC(1795)
+FUNC(1796)
+FUNC(1797)
+FUNC(1798)
+FUNC(1799)
+FUNC(1800)
+FUNC(1801)
+FUNC(1802)
+FUNC(1803)
+FUNC(1804)
+FUNC(1805)
+FUNC(1806)
+FUNC(1807)
+FUNC(1808)
+FUNC(1809)
+FUNC(1810)
+FUNC(1811)
+FUNC(1812)
+FUNC(1813)
+FUNC(1814)
+FUNC(1815)
+FUNC(1816)
+FUNC(1817)
+FUNC(1818)
+FUNC(1819)
+FUNC(1820)
+FUNC(1821)
+FUNC(1822)
+FUNC(1823)
+FUNC(1824)
+FUNC(1825)
+FUNC(1826)
+FUNC(1827)
+FUNC(1828)
+FUNC(1829)
+FUNC(1830)
+FUNC(1831)
+FUNC(1832)
+FUNC(1833)
+FUNC(1834)
+FUNC(1835)
+FUNC(1836)
+FUNC(1837)
+FUNC(1838)
+FUNC(1839)
+FUNC(1840)
+FUNC(1841)
+FUNC(1842)
+FUNC(1843)
+FUNC(1844)
+FUNC(1845)
+FUNC(1846)
+FUNC(1847)
+FUNC(1848)
+FUNC(1849)
+FUNC(1850)
+FUNC(1851)
+FUNC(1852)
+FUNC(1853)
+FUNC(1854)
+FUNC(1855)
+FUNC(1856)
+FUNC(1857)
+FUNC(1858)
+FUNC(1859)
+FUNC(1860)
+FUNC(1861)
+FUNC(1862)
+FUNC(1863)
+FUNC(1864)
+FUNC(1865)
+FUNC(1866)
+FUNC(1867)
+FUNC(1868)
+FUNC(1869)
+FUNC(1870)
+FUNC(1871)
+FUNC(1872)
+FUNC(1873)
+FUNC(1874)
+FUNC(1875)
+FUNC(1876)
+FUNC(1877)
+FUNC(1878)
+FUNC(1879)
+FUNC(1880)
+FUNC(1881)
+FUNC(1882)
+FUNC(1883)
+FUNC(1884)
+FUNC(1885)
+FUNC(1886)
+FUNC(1887)
+FUNC(1888)
+FUNC(1889)
+FUNC(1890)
+FUNC(1891)
+FUNC(1892)
+FUNC(1893)
+FUNC(1894)
+FUNC(1895)
+FUNC(1896)
+FUNC(1897)
+FUNC(1898)
+FUNC(1899)
+FUNC(1900)
+FUNC(1901)
+FUNC(1902)
+FUNC(1903)
+FUNC(1904)
+FUNC(1905)
+FUNC(1906)
+FUNC(1907)
+FUNC(1908)
+FUNC(1909)
+FUNC(1910)
+FUNC(1911)
+FUNC(1912)
+FUNC(1913)
+FUNC(1914)
+FUNC(1915)
+FUNC(1916)
+FUNC(1917)
+FUNC(1918)
+FUNC(1919)
+FUNC(1920)
+FUNC(1921)
+FUNC(1922)
+FUNC(1923)
+FUNC(1924)
+FUNC(1925)
+FUNC(1926)
+FUNC(1927)
+FUNC(1928)
+FUNC(1929)
+FUNC(1930)
+FUNC(1931)
+FUNC(1932)
+FUNC(1933)
+FUNC(1934)
+FUNC(1935)
+FUNC(1936)
+FUNC(1937)
+FUNC(1938)
+FUNC(1939)
+FUNC(1940)
+FUNC(1941)
+FUNC(1942)
+FUNC(1943)
+FUNC(1944)
+FUNC(1945)
+FUNC(1946)
+FUNC(1947)
+FUNC(1948)
+FUNC(1949)
+FUNC(1950)
+FUNC(1951)
+FUNC(1952)
+FUNC(1953)
+FUNC(1954)
+FUNC(1955)
+FUNC(1956)
+FUNC(1957)
+FUNC(1958)
+FUNC(1959)
+FUNC(1960)
+FUNC(1961)
+FUNC(1962)
+FUNC(1963)
+FUNC(1964)
+FUNC(1965)
+FUNC(1966)
+FUNC(1967)
+FUNC(1968)
+FUNC(1969)
+FUNC(1970)
+FUNC(1971)
+FUNC(1972)
+FUNC(1973)
+FUNC(1974)
+FUNC(1975)
+FUNC(1976)
+FUNC(1977)
+FUNC(1978)
+FUNC(1979)
+FUNC(1980)
+FUNC(1981)
+FUNC(1982)
+FUNC(1983)
+FUNC(1984)
+FUNC(1985)
+FUNC(1986)
+FUNC(1987)
+FUNC(1988)
+FUNC(1989)
+FUNC(1990)
+FUNC(1991)
+FUNC(1992)
+FUNC(1993)
+FUNC(1994)
+FUNC(1995)
+FUNC(1996)
+FUNC(1997)
+FUNC(1998)
+FUNC(1999)
+FUNC(2000)
--- a/sbsv2/raptor/lib/flm/test/exeabiv2_defaults.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/exeabiv2_defaults.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,48 +1,48 @@
-#
-# 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: 
-#
-##
-# Defaults for ABIv2 EXE build tests
-
-## Purpose: To enable all test makefiles to be updated rapidly
-
-
-include $(FLMHOME)/e32abiv2.mk
-
-
-DEBUG:=1
-
-CAPABILITY:=LocalServices ReadDeviceData ReadUserData
-UID1:=0x1000007a
-UID2:=0x100039ce
-UID3:=0x000001
-VID:=0x000001
-SID:=0x10003a5c
-EXETARGET:=
-TARGETTYPE:=EXE
-MAPFILENAME:=
-BMPS:=
-EPOCDATA:=
-
-VARIANTARCH:=ARMV5
-FULLVARIANTPATH=$(VARIANTARCH)/$(VARIANTTYPE)
-STATIC_LIBS_PATH:=$(call fromnativepath,$(RVCT22LIB))/armlib
-RUNTIME_LIBS_PATH=$(RELEASEPATH)/$(VARIANTARCH)/LIB
-RELEASEPATH:=$(EPOCROOT)/epoc32/release
-FLM:=e32abiv2exe.flm
-CDEFS:=$(CDEFS) __EXE__
-
-
-
+#
+# 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: 
+#
+##
+# Defaults for ABIv2 EXE build tests
+
+## Purpose: To enable all test makefiles to be updated rapidly
+
+
+include $(FLMHOME)/e32abiv2.mk
+
+
+DEBUG:=1
+
+CAPABILITY:=LocalServices ReadDeviceData ReadUserData
+UID1:=0x1000007a
+UID2:=0x100039ce
+UID3:=0x000001
+VID:=0x000001
+SID:=0x10003a5c
+EXETARGET:=
+TARGETTYPE:=EXE
+MAPFILENAME:=
+BMPS:=
+EPOCDATA:=
+
+VARIANTARCH:=ARMV5
+FULLVARIANTPATH=$(VARIANTARCH)/$(VARIANTTYPE)
+STATIC_LIBS_PATH:=$(call fromnativepath,$(RVCT22LIB))/armlib
+RUNTIME_LIBS_PATH=$(RELEASEPATH)/$(VARIANTARCH)/LIB
+RELEASEPATH:=$(EPOCROOT)/epoc32/release
+FLM:=e32abiv2exe.flm
+CDEFS:=$(CDEFS) __EXE__
+
+
+
--- a/sbsv2/raptor/lib/flm/test/exebasictests.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/exebasictests.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,30 +1,30 @@
-#
-# 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: 
-#
-##
-# A grouping glue makefile that runs all tests
-
-## Purpose: Run test makefiles in parallel to ensure that they all work
-## Postconditions: All postconditions for all the makefiles are satisfied
-
-include $(FLMHOME)/flmtools.mk
-
-$(call vsave,ALLTARGET OUTPUTPATH FART)
-COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_1.exe $(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_2.exe
-COMPONENT_GLUEMAKEFILES:=exeabiv2_1/exeabiv2_1.mk exeabiv2_2/exeabiv2_2.mk
-$(ALLTARGET):: exebasictests
-ALLTARGET:=exebasictests
-include $(FLMHOME)/grouping.flm
-$(call vrestore)
+#
+# 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: 
+#
+##
+# A grouping glue makefile that runs all tests
+
+## Purpose: Run test makefiles in parallel to ensure that they all work
+## Postconditions: All postconditions for all the makefiles are satisfied
+
+include $(FLMHOME)/flmtools.mk
+
+$(call vsave,ALLTARGET OUTPUTPATH FART)
+COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_1.exe $(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_2.exe
+COMPONENT_GLUEMAKEFILES:=exeabiv2_1/exeabiv2_1.mk exeabiv2_2/exeabiv2_2.mk
+$(ALLTARGET):: exebasictests
+ALLTARGET:=exebasictests
+include $(FLMHOME)/grouping.flm
+$(call vrestore)
--- a/sbsv2/raptor/lib/flm/test/exeperftests.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/exeperftests.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,31 +1,31 @@
-#
-# 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: 
-#
-##
-# A grouping glue makefile that runs all tests
-
-## Purpose: Run test makefiles in parallel to ensure that they all work
-## Postconditions: All postconditions for all the makefiles are satisfied
-
-include $(FLMHOME)/flmtools.mk
-
-$(call vsave,ALLTARGET OUTPUTPATH)
-COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_3.exe $(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_4.exe
-COMPONENT_GLUEMAKEFILES:=exeabiv2_3/exeabiv2_3.mk exeabiv2_4/exeabiv2_4.mk
-$(ALLTARGET):: exeperftests
-ALLTARGET:=exeperftests
-
-include $(FLMHOME)/grouping.flm
-$(call vrestore)
+#
+# 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: 
+#
+##
+# A grouping glue makefile that runs all tests
+
+## Purpose: Run test makefiles in parallel to ensure that they all work
+## Postconditions: All postconditions for all the makefiles are satisfied
+
+include $(FLMHOME)/flmtools.mk
+
+$(call vsave,ALLTARGET OUTPUTPATH)
+COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_3.exe $(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_4.exe
+COMPONENT_GLUEMAKEFILES:=exeabiv2_3/exeabiv2_3.mk exeabiv2_4/exeabiv2_4.mk
+$(ALLTARGET):: exeperftests
+ALLTARGET:=exeperftests
+
+include $(FLMHOME)/grouping.flm
+$(call vrestore)
--- a/sbsv2/raptor/lib/flm/test/export1/Makefile	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/export1/Makefile	Wed Jun 23 16:56:47 2010 +0800
@@ -1,10 +1,10 @@
-
-EXPORT:=testexport/test1exp.h<-t1e.h \
-	testexport/test2exp.h<-t2e.h \
-	testexport/test3exp.h<-t1e.h \
-	testexport/test4exp.h<-t2e.h
-
-ALLTARGET:=all
-
-include $(FLMHOME)/export.flm
-
+
+EXPORT:=testexport/test1exp.h<-t1e.h \
+	testexport/test2exp.h<-t2e.h \
+	testexport/test3exp.h<-t1e.h \
+	testexport/test4exp.h<-t2e.h
+
+ALLTARGET:=all
+
+include $(FLMHOME)/export.flm
+
--- a/sbsv2/raptor/lib/flm/test/export1/t1e.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/export1/t1e.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,20 +1,20 @@
-/*
-* 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: 
-*
-*/
-/*
-  test header file.
-
-*/
+/*
+* 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: 
+*
+*/
+/*
+  test header file.
+
+*/
--- a/sbsv2/raptor/lib/flm/test/export1/t2e.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/export1/t2e.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,20 +1,20 @@
-/*
-* 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: 
-*
-*/
-/*
-  test header file.
-
-*/
+/*
+* 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: 
+*
+*/
+/*
+  test header file.
+
+*/
--- a/sbsv2/raptor/lib/flm/test/export1/t3e.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/export1/t3e.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,20 +1,20 @@
-/*
-* 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: 
-*
-*/
-/*
-  test header file.
-
-*/
+/*
+* 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: 
+*
+*/
+/*
+  test header file.
+
+*/
--- a/sbsv2/raptor/lib/flm/test/export1/t4e.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/export1/t4e.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,20 +1,20 @@
-/*
-* 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: 
-*
-*/
-/*
-  test header file.
-
-*/
+/*
+* 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: 
+*
+*/
+/*
+  test header file.
+
+*/
--- a/sbsv2/raptor/lib/flm/test/flmtests.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/flmtests.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,35 +1,35 @@
-#
-# 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: 
-#
-##
-# A grouping glue makefile that runs all tests
-
-## Purpose: Run test makefiles in parallel to ensure that they all work
-## Postconditions: All postconditions for all the makefiles are satisfied
-
-#COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_1/exeabiv2_1.exe
-#COMPONENT_GLUEMAKEFILES:=exeabiv2_1/exeabiv2_1.mk
-
-#COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_1/exeabiv2_1.exe $(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_2/exeabiv2_2.exe $(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_3/exeabiv2_3.exe $(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_4/exeabiv2_4.exe
-#COMPONENT_GLUEMAKEFILES:=exeabiv2_1/exeabiv2_1.mk exeabiv2_2/exeabiv2_2.mk exeabiv2_3/exeabiv2_3.mk exeabiv2_4/exeabiv2_4.mk
-
-
-#COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/nothing/nothing.mk
-#COMPONENT_GLUEMAKEFILES:=nothing/nothing.mk
-
-COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/ciaabiv2_1
-COMPONENT_GLUEMAKEFILES:=ciaabiv2_1/ciaabiv2_1.mk
-
-include $(FLMHOME)/grouping.flm
+#
+# 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: 
+#
+##
+# A grouping glue makefile that runs all tests
+
+## Purpose: Run test makefiles in parallel to ensure that they all work
+## Postconditions: All postconditions for all the makefiles are satisfied
+
+#COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_1/exeabiv2_1.exe
+#COMPONENT_GLUEMAKEFILES:=exeabiv2_1/exeabiv2_1.mk
+
+#COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_1/exeabiv2_1.exe $(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_2/exeabiv2_2.exe $(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_3/exeabiv2_3.exe $(RELEASEPATH)/$(FULLVARIANTPATH)/exeabiv2_4/exeabiv2_4.exe
+#COMPONENT_GLUEMAKEFILES:=exeabiv2_1/exeabiv2_1.mk exeabiv2_2/exeabiv2_2.mk exeabiv2_3/exeabiv2_3.mk exeabiv2_4/exeabiv2_4.mk
+
+
+#COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/nothing/nothing.mk
+#COMPONENT_GLUEMAKEFILES:=nothing/nothing.mk
+
+COMPONENT_ALLTARGETS:=$(RELEASEPATH)/$(FULLVARIANTPATH)/ciaabiv2_1
+COMPONENT_GLUEMAKEFILES:=ciaabiv2_1/ciaabiv2_1.mk
+
+include $(FLMHOME)/grouping.flm
--- a/sbsv2/raptor/lib/flm/test/raptorglue/raptorglue.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/raptorglue/raptorglue.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,133 +1,133 @@
-
-# test a "real" raptor gluefile
-# generated by Raptor 0.0.1
-
-RAPTOR_HOME?=/localhome/tmurphy/pf/EPOC/development/tools/personal/tmurphy/tools/raptor
-EPOCROOT?=/tmp/tim-epocroot/
-
-# start simple 
-
-# configuration ARMV5_UDEB
-AAPCS_OPTION:=--apcs /inter
-CAPABILITY:=LocalServices ReadDeviceData ReadUserData
-CC:=armcc
-CC_ERRORS_CONTROL_OPTION:=--diag_error 1267
-CC_WARNINGS_CONTROL_OPTION:=--diag_suppress 161,611,654,997,1152,1300,1464,1488,6318
-CDEFS:=__MARM_THUMB__ __MARM_INTERWORK__ _UNICODE __SYMBIAN32__ __ARMCC__ __EPOC32__ __MARM__ __EABI__ __PRODUCT_INCLUDE=\"$(EPOCROOT)/epoc32/include/variant/Symbian_OS_vFuture.hrh\" _EXE_
-CFLAGS:=
-COMMANDFILE_OPTION:=--via
-COMPILE_ONLY_OPTION:=-c
-CPP_LANG_OPTION:=--cpp
-CREATABLEPATHS:=
-SOURCEFILES:=$(RAPTOR_HOME)/test/simple/test.cpp
-ELF2E32:=$(EPOCROOT)/epoc32/tools/elf2e32$(DOTEXE)
-ENUM_OPTION:=--enum_is_int
-EXCEPTIONS:=--exceptions --exceptions_unwind
-EXEBASELIBS:=usrt2_2.lib euser.dso efsrv.dso bafl.dso commsdat.dso
-EXENAME:=test
-EXPORT_VTBL_OPTION:=--export_all_vtbl
-FLMHOME:=$(RAPTOR_HOME)/lib/flm
-FPMODE_OPTION:=--fpmode ieee_no_fenv
-FULLVARIANTPATH:=ARMV5/UDEB
-INCLUDES:=-J $(EPOCROOT)/epoc32/include -J $(EPOCROOT)/epoc32/include/variant
-LD:=armlink
-LIBPATH:=
-LINKER_DEBUG_OPTION:=--debug
-LINKER_ENTRY_OPTION:=--entry
-LINKER_SYMBOLS_FILE_OPTION:=--list
-LINKER_SYMBOLS_OPTION:=--symbols
-OUTPUTPATH:=$(EPOCROOT)/epoc32/build
-OUTPUT_OPTION:=-o
-OWN_LIBRARY_OPTION:=-Ono_known_library
-PREINCLUDE_OPTION:=--preinclude $(EPOCROOT)/epoc32/include/rvct2_2/rvct2_2.h
-RELEASEPATH:=$(EPOCROOT)/epoc32/release
-RUNTIME_LIBS_LIST:=drtaeabi.dso dfpaeabi.dso dfprvct2_2.dso scppnwdl.dso drtrvct2_2.dso
-RUNTIME_LIBS_PATH:=$(EPOCROOT)/epoc32/release/ARMV5,$(EPOCROOT)/epoc32/release/ARMV5/LIB
-RUNTIME_SYMBOL_VISIBILITY_OPTION:=--dllimport_runtime
-RW_BASE_OPTION:=--rw-base
-SHARED_OBJECT_OPTION:=--dll
-SID:=0x10003a5c
-SOFTVFPMODE_OPTION:=
-SO_NAME_OPTION:=--soname
-SPLIT_OPTION:=--split
-STACKSIZE:=0x00005000
-STATIC_LIBS_LIST:="h_t__uf.l(switch8.o)"
-STATIC_LIBS_PATH:=/usr/local/ARM/RVCT/Data/2.2/308/lib/armlib
-SYMBIAN_CCFLAGS:=-g -O0
-SYMBIAN_LINK_FLAGS:=--diag_suppress 6331  --bpabi --reloc   --no_scanlib --datacompressor=off
-SYMVER_OPTION:=--symver_soname
-TARGETTYPE:=EXE
-TARGET_ARCH_OPTION:=--cpu 5T
-THUMB_INSTRUCTION_SET:=--thumb
-UID1:=0x1000007a
-UID2:=0x100039ce
-UID3:=0x00000001
-USER_LIBS_PATH_OPTION:=--userlibpath
-VARIANTTYPE:=UDEB
-VFE_OPTION:=--no_vfe
-include $(FLMHOME)/e32abiv2exe.flm
-
-
-# configuration ARMV5_UREL
-AAPCS_OPTION:=--apcs /inter
-CAPABILITY:=LocalServices ReadDeviceData ReadUserData
-CC:=armcc
-CC_ERRORS_CONTROL_OPTION:=--diag_error 1267
-CC_WARNINGS_CONTROL_OPTION:=--diag_suppress 161,611,654,997,1152,1300,1464,1488,6318
-CDEFS:=__MARM_THUMB__ __MARM_INTERWORK__ _UNICODE __SYMBIAN32__ __ARMCC__ __EPOC32__ __MARM__ __EABI__ __PRODUCT_INCLUDE=\"$(EPOCROOT)/epoc32/include/variant/Symbian_OS_vFuture.hrh\" _EXE_
-CFLAGS:=
-COMMANDFILE_OPTION:=--via
-COMPILE_ONLY_OPTION:=-c
-CPP_LANG_OPTION:=--cpp
-CREATABLEPATHS:=
-SOURCEFILES:=$(RAPTOR_HOME)/test/simple/test.cpp
-ELF2E32:=$(EPOCROOT)/epoc32/tools/elf2e32$(DOTEXE)
-ENUM_OPTION:=--enum_is_int
-EXCEPTIONS:=--exceptions --exceptions_unwind
-EXEBASELIBS:=usrt2_2.lib euser.dso efsrv.dso bafl.dso commsdat.dso
-EXENAME:=test
-EXPORT_VTBL_OPTION:=--export_all_vtbl
-FLMHOME:=$(RAPTOR_HOME)/lib/flm
-FPMODE_OPTION:=--fpmode ieee_no_fenv
-FULLVARIANTPATH:=ARMV5/UREL
-INCLUDES:=-J $(EPOCROOT)/epoc32/include -J $(EPOCROOT)/epoc32/include/variant
-LD:=armlink
-LIBPATH:=
-LINKER_DEBUG_OPTION:=--debug
-LINKER_ENTRY_OPTION:=--entry
-LINKER_SYMBOLS_FILE_OPTION:=--list
-LINKER_SYMBOLS_OPTION:=--symbols
-OUTPUTPATH:=$(EPOCROOT)/epoc32/build
-OUTPUT_OPTION:=-o
-OWN_LIBRARY_OPTION:=-Ono_known_library
-PREINCLUDE_OPTION:=--preinclude $(EPOCROOT)/epoc32/include/rvct2_2/rvct2_2.h
-RELEASEPATH:=$(EPOCROOT)/epoc32/release
-RUNTIME_LIBS_LIST:=drtaeabi.dso dfpaeabi.dso dfprvct2_2.dso scppnwdl.dso drtrvct2_2.dso
-RUNTIME_LIBS_PATH:=$(EPOCROOT)/epoc32/release/ARMV5,$(EPOCROOT)/epoc32/release/ARMV5/LIB
-RUNTIME_SYMBOL_VISIBILITY_OPTION:=--dllimport_runtime
-RW_BASE_OPTION:=--rw-base
-SHARED_OBJECT_OPTION:=--dll
-SID:=0x10003a5c
-SOFTVFPMODE_OPTION:=
-SO_NAME_OPTION:=--soname
-SPLIT_OPTION:=--split
-STACKSIZE:=0x00005000
-STATIC_LIBS_LIST:="h_t__uf.l(switch8.o)"
-STATIC_LIBS_PATH:=/usr/local/ARM/RVCT/Data/2.2/308/lib/armlib
-SYMBIAN_CCFLAGS:=-O2
-SYMBIAN_LINK_FLAGS:=--diag_suppress 6331  --bpabi --reloc   --no_scanlib --datacompressor=off
-SYMVER_OPTION:=--symver_soname
-TARGETTYPE:=EXE
-TARGET_ARCH_OPTION:=--cpu 5T
-THUMB_INSTRUCTION_SET:=--thumb
-UID1:=0x1000007a
-UID2:=0x100039ce
-UID3:=0x00000001
-USER_LIBS_PATH_OPTION:=--userlibpath
-VARIANTTYPE:=UREL
-VFE_OPTION:=--no_vfe
-include $(FLMHOME)/e32abiv2exe.flm
-
-# end simple 
-
-# END OF GENERATED MAKEFILE : DO NOT EDIT
+
+# test a "real" raptor gluefile
+# generated by Raptor 0.0.1
+
+RAPTOR_HOME?=/localhome/tmurphy/pf/EPOC/development/tools/personal/tmurphy/tools/raptor
+EPOCROOT?=/tmp/tim-epocroot/
+
+# start simple 
+
+# configuration ARMV5_UDEB
+AAPCS_OPTION:=--apcs /inter
+CAPABILITY:=LocalServices ReadDeviceData ReadUserData
+CC:=armcc
+CC_ERRORS_CONTROL_OPTION:=--diag_error 1267
+CC_WARNINGS_CONTROL_OPTION:=--diag_suppress 161,611,654,997,1152,1300,1464,1488,6318
+CDEFS:=__MARM_THUMB__ __MARM_INTERWORK__ _UNICODE __SYMBIAN32__ __ARMCC__ __EPOC32__ __MARM__ __EABI__ __PRODUCT_INCLUDE=\"$(EPOCROOT)/epoc32/include/variant/Symbian_OS_vFuture.hrh\" _EXE_
+CFLAGS:=
+COMMANDFILE_OPTION:=--via
+COMPILE_ONLY_OPTION:=-c
+CPP_LANG_OPTION:=--cpp
+CREATABLEPATHS:=
+SOURCEFILES:=$(RAPTOR_HOME)/test/simple/test.cpp
+ELF2E32:=$(EPOCROOT)/epoc32/tools/elf2e32$(DOTEXE)
+ENUM_OPTION:=--enum_is_int
+EXCEPTIONS:=--exceptions --exceptions_unwind
+EXEBASELIBS:=usrt2_2.lib euser.dso efsrv.dso bafl.dso commsdat.dso
+EXENAME:=test
+EXPORT_VTBL_OPTION:=--export_all_vtbl
+FLMHOME:=$(RAPTOR_HOME)/lib/flm
+FPMODE_OPTION:=--fpmode ieee_no_fenv
+FULLVARIANTPATH:=ARMV5/UDEB
+INCLUDES:=-J $(EPOCROOT)/epoc32/include -J $(EPOCROOT)/epoc32/include/variant
+LD:=armlink
+LIBPATH:=
+LINKER_DEBUG_OPTION:=--debug
+LINKER_ENTRY_OPTION:=--entry
+LINKER_SYMBOLS_FILE_OPTION:=--list
+LINKER_SYMBOLS_OPTION:=--symbols
+OUTPUTPATH:=$(EPOCROOT)/epoc32/build
+OUTPUT_OPTION:=-o
+OWN_LIBRARY_OPTION:=-Ono_known_library
+PREINCLUDE_OPTION:=--preinclude $(EPOCROOT)/epoc32/include/rvct2_2/rvct2_2.h
+RELEASEPATH:=$(EPOCROOT)/epoc32/release
+RUNTIME_LIBS_LIST:=drtaeabi.dso dfpaeabi.dso dfprvct2_2.dso scppnwdl.dso drtrvct2_2.dso
+RUNTIME_LIBS_PATH:=$(EPOCROOT)/epoc32/release/ARMV5,$(EPOCROOT)/epoc32/release/ARMV5/LIB
+RUNTIME_SYMBOL_VISIBILITY_OPTION:=--dllimport_runtime
+RW_BASE_OPTION:=--rw-base
+SHARED_OBJECT_OPTION:=--dll
+SID:=0x10003a5c
+SOFTVFPMODE_OPTION:=
+SO_NAME_OPTION:=--soname
+SPLIT_OPTION:=--split
+STACKSIZE:=0x00005000
+STATIC_LIBS_LIST:="h_t__uf.l(switch8.o)"
+STATIC_LIBS_PATH:=/usr/local/ARM/RVCT/Data/2.2/308/lib/armlib
+SYMBIAN_CCFLAGS:=-g -O0
+SYMBIAN_LINK_FLAGS:=--diag_suppress 6331  --bpabi --reloc   --no_scanlib --datacompressor=off
+SYMVER_OPTION:=--symver_soname
+TARGETTYPE:=EXE
+TARGET_ARCH_OPTION:=--cpu 5T
+THUMB_INSTRUCTION_SET:=--thumb
+UID1:=0x1000007a
+UID2:=0x100039ce
+UID3:=0x00000001
+USER_LIBS_PATH_OPTION:=--userlibpath
+VARIANTTYPE:=UDEB
+VFE_OPTION:=--no_vfe
+include $(FLMHOME)/e32abiv2exe.flm
+
+
+# configuration ARMV5_UREL
+AAPCS_OPTION:=--apcs /inter
+CAPABILITY:=LocalServices ReadDeviceData ReadUserData
+CC:=armcc
+CC_ERRORS_CONTROL_OPTION:=--diag_error 1267
+CC_WARNINGS_CONTROL_OPTION:=--diag_suppress 161,611,654,997,1152,1300,1464,1488,6318
+CDEFS:=__MARM_THUMB__ __MARM_INTERWORK__ _UNICODE __SYMBIAN32__ __ARMCC__ __EPOC32__ __MARM__ __EABI__ __PRODUCT_INCLUDE=\"$(EPOCROOT)/epoc32/include/variant/Symbian_OS_vFuture.hrh\" _EXE_
+CFLAGS:=
+COMMANDFILE_OPTION:=--via
+COMPILE_ONLY_OPTION:=-c
+CPP_LANG_OPTION:=--cpp
+CREATABLEPATHS:=
+SOURCEFILES:=$(RAPTOR_HOME)/test/simple/test.cpp
+ELF2E32:=$(EPOCROOT)/epoc32/tools/elf2e32$(DOTEXE)
+ENUM_OPTION:=--enum_is_int
+EXCEPTIONS:=--exceptions --exceptions_unwind
+EXEBASELIBS:=usrt2_2.lib euser.dso efsrv.dso bafl.dso commsdat.dso
+EXENAME:=test
+EXPORT_VTBL_OPTION:=--export_all_vtbl
+FLMHOME:=$(RAPTOR_HOME)/lib/flm
+FPMODE_OPTION:=--fpmode ieee_no_fenv
+FULLVARIANTPATH:=ARMV5/UREL
+INCLUDES:=-J $(EPOCROOT)/epoc32/include -J $(EPOCROOT)/epoc32/include/variant
+LD:=armlink
+LIBPATH:=
+LINKER_DEBUG_OPTION:=--debug
+LINKER_ENTRY_OPTION:=--entry
+LINKER_SYMBOLS_FILE_OPTION:=--list
+LINKER_SYMBOLS_OPTION:=--symbols
+OUTPUTPATH:=$(EPOCROOT)/epoc32/build
+OUTPUT_OPTION:=-o
+OWN_LIBRARY_OPTION:=-Ono_known_library
+PREINCLUDE_OPTION:=--preinclude $(EPOCROOT)/epoc32/include/rvct2_2/rvct2_2.h
+RELEASEPATH:=$(EPOCROOT)/epoc32/release
+RUNTIME_LIBS_LIST:=drtaeabi.dso dfpaeabi.dso dfprvct2_2.dso scppnwdl.dso drtrvct2_2.dso
+RUNTIME_LIBS_PATH:=$(EPOCROOT)/epoc32/release/ARMV5,$(EPOCROOT)/epoc32/release/ARMV5/LIB
+RUNTIME_SYMBOL_VISIBILITY_OPTION:=--dllimport_runtime
+RW_BASE_OPTION:=--rw-base
+SHARED_OBJECT_OPTION:=--dll
+SID:=0x10003a5c
+SOFTVFPMODE_OPTION:=
+SO_NAME_OPTION:=--soname
+SPLIT_OPTION:=--split
+STACKSIZE:=0x00005000
+STATIC_LIBS_LIST:="h_t__uf.l(switch8.o)"
+STATIC_LIBS_PATH:=/usr/local/ARM/RVCT/Data/2.2/308/lib/armlib
+SYMBIAN_CCFLAGS:=-O2
+SYMBIAN_LINK_FLAGS:=--diag_suppress 6331  --bpabi --reloc   --no_scanlib --datacompressor=off
+SYMVER_OPTION:=--symver_soname
+TARGETTYPE:=EXE
+TARGET_ARCH_OPTION:=--cpu 5T
+THUMB_INSTRUCTION_SET:=--thumb
+UID1:=0x1000007a
+UID2:=0x100039ce
+UID3:=0x00000001
+USER_LIBS_PATH_OPTION:=--userlibpath
+VARIANTTYPE:=UREL
+VFE_OPTION:=--no_vfe
+include $(FLMHOME)/e32abiv2exe.flm
+
+# end simple 
+
+# END OF GENERATED MAKEFILE : DO NOT EDIT
--- a/sbsv2/raptor/lib/flm/test/templateext/Makefile	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/templateext/Makefile	Wed Jun 23 16:56:47 2010 +0800
@@ -1,48 +1,48 @@
-include $(FLMHOME)/flmtools.mk
-
-
-
-EPOCROOT:=fred1
-PLATFORM:=fred1
-CFG:=fred1
-TO_ROOT:=fred1
-TO_BLDINF:=fred1
-EPOCBLD:=fred1
-EXTENSION_ROOT:=fred1
-HOST_SHELL:=fred1
-PLATFORM_PATH:=fred1
-CFG_PATH:=fred1
-TEMPLATE_EXTENSION_MAKEFILE:=temex.mk
-HALPATH:=fred1/..
-
-include $(FLMHOME)/template_ext.flm
-
-
-EPOCROOT:=alice2
-PLATFORM:=alice2
-CFG:=alice2
-TO_ROOT:=alice2
-TO_BLDINF:=alice2
-EPOCBLD:=alice2
-EXTENSION_ROOT:=alice2
-HOST_SHELL:=alice2
-PLATFORM_PATH:=alice2
-CFG_PATH:=alice2
-TEMPLATE_EXTENSION_MAKEFILE:=temex.mk
-
-include $(FLMHOME)/template_ext.flm
-
-
-EPOCROOT:=test1
-PLATFORM:=test2
-CFG:=test3
-TO_ROOT:=test4
-TO_BLDINF:=test5
-EPOCBLD:=test6
-EXTENSION_ROOT:=test7
-HOST_SHELL:=test8
-PLATFORM_PATH:=test16
-CFG_PATH:=test17
-TEMPLATE_EXTENSION_MAKEFILE:=temex.mk
-
-include $(FLMHOME)/template_ext.flm
+include $(FLMHOME)/flmtools.mk
+
+
+
+EPOCROOT:=fred1
+PLATFORM:=fred1
+CFG:=fred1
+TO_ROOT:=fred1
+TO_BLDINF:=fred1
+EPOCBLD:=fred1
+EXTENSION_ROOT:=fred1
+HOST_SHELL:=fred1
+PLATFORM_PATH:=fred1
+CFG_PATH:=fred1
+TEMPLATE_EXTENSION_MAKEFILE:=temex.mk
+HALPATH:=fred1/..
+
+include $(FLMHOME)/template_ext.flm
+
+
+EPOCROOT:=alice2
+PLATFORM:=alice2
+CFG:=alice2
+TO_ROOT:=alice2
+TO_BLDINF:=alice2
+EPOCBLD:=alice2
+EXTENSION_ROOT:=alice2
+HOST_SHELL:=alice2
+PLATFORM_PATH:=alice2
+CFG_PATH:=alice2
+TEMPLATE_EXTENSION_MAKEFILE:=temex.mk
+
+include $(FLMHOME)/template_ext.flm
+
+
+EPOCROOT:=test1
+PLATFORM:=test2
+CFG:=test3
+TO_ROOT:=test4
+TO_BLDINF:=test5
+EPOCBLD:=test6
+EXTENSION_ROOT:=test7
+HOST_SHELL:=test8
+PLATFORM_PATH:=test16
+CFG_PATH:=test17
+TEMPLATE_EXTENSION_MAKEFILE:=temex.mk
+
+include $(FLMHOME)/template_ext.flm
--- a/sbsv2/raptor/lib/flm/test/templateext/temex.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/test/templateext/temex.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,96 +1,96 @@
-#
-# 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: 
-#
-#
-# A test-template extension makefile
-# supposed to demonstrate that different calls
-# to the same template extension makefile will
-# get different variable values.
-# i.e. it's supposed to show target specific variables 
-# working properly for template extension makefiles.
-
-# The test is by manual comparison at the moment.
-
-
-
-define print
-echo ""
-echo ""
-@echo ""
-@echo "EPOCROOT=$(EPOCROOT)"
-@echo "PLATFORM=$(PLATFORM)"
-@echo "CFG=$(CFG)"
-@echo "TO_ROOT=$(TO_ROOT)"
-@echo "TO_BLDINF=$(TO_BLDINF)"
-@echo "EPOCBLD=$(EPOCBLD)"
-@echo "EXTENSION_ROOT=$(EXTENSION_ROOT)"
-@echo "HOST_SHELL=$(HOST_SHELL)"
-@echo "/=$(/)"
-@echo ";=$(;)"
-@echo "RMDIR=$(RMDIR)"
-@echo "RM=$(RM)"
-@echo "ERASE=$(ERASE)"
-@echo "MKDIR=$(MKDIR)"
-@echo "CP=$(CP)"
-@echo "PLATFORM_PATH=$(PLATFORM_PATH)"
-@echo "CFG_PATH=$(CFG_PATH)"
-@echo "TEMPLATE_EXTENSION_MAKEFILE=$(TEMPLATE_EXTENSION_MAKEFILE)"
-endef
-
-DO_NOTHING :
-	@echo "DO_NOTHING"
-	$(print)
-
-
-MAKMAKE :
-	@echo "MAKMAKE"
-	$(print)
-
-BLD :
-	@echo "BLD"
-	$(print)
-
-SAVESPACE :
-	@echo "SAVESPACE"
-	$(print)
-
-FREEZE :
-	@echo "FREEZE"
-	$(print)
-
-LIB :
-	@echo "LIB"
-	$(print)
-
-CLEANLIB :
-	@echo "CLEANLIB"
-	$(print)
-
-RESOURCE :
-	@echo "RESOURCE"
-	$(print)
-
-CLEAN :
-	@echo "CLEAN"
-	$(print)
-
-RELEASABLES :
-	@echo "RELEASABLES"
-	$(print)
-
-FINAL :
-	@echo "FINAL"
-	$(print)
-
+#
+# 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: 
+#
+#
+# A test-template extension makefile
+# supposed to demonstrate that different calls
+# to the same template extension makefile will
+# get different variable values.
+# i.e. it's supposed to show target specific variables 
+# working properly for template extension makefiles.
+
+# The test is by manual comparison at the moment.
+
+
+
+define print
+echo ""
+echo ""
+@echo ""
+@echo "EPOCROOT=$(EPOCROOT)"
+@echo "PLATFORM=$(PLATFORM)"
+@echo "CFG=$(CFG)"
+@echo "TO_ROOT=$(TO_ROOT)"
+@echo "TO_BLDINF=$(TO_BLDINF)"
+@echo "EPOCBLD=$(EPOCBLD)"
+@echo "EXTENSION_ROOT=$(EXTENSION_ROOT)"
+@echo "HOST_SHELL=$(HOST_SHELL)"
+@echo "/=$(/)"
+@echo ";=$(;)"
+@echo "RMDIR=$(RMDIR)"
+@echo "RM=$(RM)"
+@echo "ERASE=$(ERASE)"
+@echo "MKDIR=$(MKDIR)"
+@echo "CP=$(CP)"
+@echo "PLATFORM_PATH=$(PLATFORM_PATH)"
+@echo "CFG_PATH=$(CFG_PATH)"
+@echo "TEMPLATE_EXTENSION_MAKEFILE=$(TEMPLATE_EXTENSION_MAKEFILE)"
+endef
+
+DO_NOTHING :
+	@echo "DO_NOTHING"
+	$(print)
+
+
+MAKMAKE :
+	@echo "MAKMAKE"
+	$(print)
+
+BLD :
+	@echo "BLD"
+	$(print)
+
+SAVESPACE :
+	@echo "SAVESPACE"
+	$(print)
+
+FREEZE :
+	@echo "FREEZE"
+	$(print)
+
+LIB :
+	@echo "LIB"
+	$(print)
+
+CLEANLIB :
+	@echo "CLEANLIB"
+	$(print)
+
+RESOURCE :
+	@echo "RESOURCE"
+	$(print)
+
+CLEAN :
+	@echo "CLEAN"
+	$(print)
+
+RELEASABLES :
+	@echo "RELEASABLES"
+	$(print)
+
+FINAL :
+	@echo "FINAL"
+	$(print)
+
--- a/sbsv2/raptor/lib/flm/tools.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/tools.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,58 +1,61 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
-	<!-- Tools interfaces -->
-
-	<interface name="Tools.common" abstract="true" extends="base.flm">
-		<param name='CDEFS.WIN32' default=''/>
-		<param name='CDEFS.LINUX' default=''/>
-		<param name='CDEFS'/>
-		<param name='CFLAGS'/>
-		<param name='CFLAGS.WIN32'/>
-		<param name='COMPILER'/>
-		<param name='COMPILER_PATH.WIN32'/>
-		<param name='COMPILER_PATH.LINUX'/>
-		<param name='INC.COMPILER' default=''/>
-		<param name='MMPDEFS' default=''/>
-		<param name='OPT.D'/>
-		<param name='OPT.O'/>
-		<param name='OPT.PREINCLUDE'/>
-		<param name='OPT.SYSTEMINCLUDE'/>
-		<param name='OPT.USERINCLUDE'/>
-		<param name='OPTION_GCC' default=''/>
-		<param name='OUTPUTPATH'/>
-		<param name='VARIANTPLATFORM'/>
-		<param name='PLATFORM' default='$(VARIANTPLATFORM)'/>
-		<param name='RELEASEPATH'/>
-		<param name='SOURCE'/>
-		<param name='SYSTEMINCLUDE' default=''/>
-		<param name='TARGET'/>
-		<param name='TOOLSPATH'/>
-		<param name='USERINCLUDE' default=''/>
-		<param name='PRODUCT_INCLUDE' default=''/>
-		<param name='PLATMACROS.WINDOWS'/>
-		<param name='PLATMACROS.LINUX'/>
-		<param name='VARIANTTYPE'/>
-	</interface>
-
-	<interface name="Tools.exe" extends="Tools.common" flm="tools2exe.flm">
-		<param name='LINKER'/>
-		<param name='LFLAGS'/>
-		<param name='LIBS.WIN32' default=''/>
-		<param name='LIBS.LINUX' default=''/>
-		<param name='OPT.L'/>
-		<param name='OPT.l'/>
-		<param name='STATICLIBRARY'/>
-		<param name='TARGETTYPE' default="EXE"/>
-	</interface>
-
-	<interface name="Tools.lib" extends="Tools.common" flm="tools2lib.flm">
-		<param name='ARCHIVER'/>
-		<param name='RANLIB'/>
-		<param name='AFLAGS'/>
-		<param name='TARGETTYPE' default="LIB"/>
-	</interface>
-
-	<interface name="Tools.extension" extends="base.extension" flm="template_ext.flm">
-	</interface>
-
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../schema/build/2_0.xsd">
+	<!-- Tools interfaces -->
+
+	<interface name="Tools.common" abstract="true" extends="base.flm">
+		<param name='CDEFS.WIN32' default=''/>
+		<param name='CDEFS.LINUX' default=''/>
+		<param name='CDEFS'/>
+		<param name='CFLAGS'/>
+		<param name='CFLAGS.WIN32'/>
+		<param name='COMPILER'/>
+		<param name='COMPILER_PATH.WIN32'/>
+		<param name='COMPILER_PATH.LINUX'/>
+		<param name='INC.COMPILER' default=''/>
+		<param name='MMPDEFS' default=''/>
+		<param name='OPT.D'/>
+		<param name='OPT.O'/>
+		<param name='OPT.PREINCLUDE'/>
+		<param name='OPT.SYSTEMINCLUDE'/>
+		<param name='OPT.USERINCLUDE'/>
+		<param name='OPTION_GCC' default=''/>
+		<param name='OUTPUTPATH'/>
+		<param name='VARIANTPLATFORM'/>
+		<param name='PLATFORM' default='$(VARIANTPLATFORM)'/>
+		<param name='RELEASEPATH'/>
+		<param name='SOURCE'/>
+		<param name='SYSTEMINCLUDE' default=''/>
+		<param name='TARGET'/>
+		<param name='TOOLSPATH'/>
+		<param name='TOOLS2WIN32' default=''/>
+		<param name='USERINCLUDE' default=''/>
+		<param name='PRODUCT_INCLUDE' default=''/>
+		<param name='PLATMACROS.WINDOWS'/>
+		<param name='PLATMACROS.LINUX'/>
+		<param name='VARIANTTYPE'/>
+	</interface>
+
+	<interface name="Tools.exe" extends="Tools.common" flm="tools2exe.flm">
+		<param name='DOTEXE'/>
+		<param name='LINKER'/>
+		<param name='LFLAGS'/>
+		<param name='LIBS.WIN32' default=''/>
+		<param name='LIBS.LINUX' default=''/>
+		<param name='OPT.L'/>
+		<param name='OPT.l'/>
+		<param name='STATICLIBRARY'/>
+		<param name='TARGETTYPE' default="EXE"/>
+		<param name='LINKER_OPTIONS' default=''/>	
+	</interface>
+
+	<interface name="Tools.lib" extends="Tools.common" flm="tools2lib.flm">
+		<param name='ARCHIVER'/>
+		<param name='RANLIB'/>
+		<param name='AFLAGS'/>
+		<param name='TARGETTYPE' default="LIB"/>
+	</interface>
+
+	<interface name="Tools.extension" extends="base.extension" flm="template_ext.flm">
+	</interface>
+
+</build>
--- a/sbsv2/raptor/lib/flm/tools/buildstubsis.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/tools/buildstubsis.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,50 +1,50 @@
-# 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:
-#
-
-# FLM to build StubSis libraries.
-
-## Outputs - externally relevant targets that this FLM generates
-
-TARGETDIR:=$(EPOCROOT)/epoc32/data/z/system/install
-
-ifeq ($(PLATFORM),WINSCW)
-	TARGETDIR:=$(EPOCROOT)/epoc32/release/$(PLATFORM_PATH)/$(CFG_PATH)/z/system/install
-endif
-
-$(call makepath,$(TARGETDIR))
-
-# This section is in a macro oherwise startrule could get wrong values
-define SisFileCreation
-$(SISFILE): $(EXTENSION_ROOT)/$(SRCDIR)/$(SISNAME).pkg
-	$(call startrule,stubsis) \
-	$(EPOCROOT)/epoc32/tools/makesis$(DOTEXE) -s $$? $$@  \
-	$(call endrule,stubsis)
-endef
-
-# Build stub SIS file
-SISFILE:= $(TARGETDIR)/$(SISNAME).sis
-# Here a variable named "done_<sanitised $SISFILE>" gets created
-GUARD:=done_$(call sanitise,$(SISFILE))
-# If variable "done_..." not set, set it to 1, so that
-# UREL and UDEB do not execute makesis twice on the same target 
-ifeq ($($(GUARD)),)
-$(GUARD):=1
-ALL:: $(SISFILE)
-$(eval $(call SisFileCreation))
-$(eval $(call whatmacro,$(SISFILE)))
-$(eval $(call GenerateStandardCleanTarget,$(SISFILE),$(TARGETDIR)))
-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:
+#
+
+# FLM to build StubSis libraries.
+
+## Outputs - externally relevant targets that this FLM generates
+
+TARGETDIR:=$(EPOCROOT)/epoc32/data/z/system/install
+
+ifeq ($(PLATFORM),WINSCW)
+	TARGETDIR:=$(EPOCROOT)/epoc32/release/$(PLATFORM_PATH)/$(CFG_PATH)/z/system/install
+endif
+
+$(call makepath,$(TARGETDIR))
+
+# This section is in a macro oherwise startrule could get wrong values
+define SisFileCreation
+$(SISFILE): $(EXTENSION_ROOT)/$(SRCDIR)/$(SISNAME).pkg
+	$(call startrule,stubsis) \
+	$(EPOCROOT)/epoc32/tools/makesis$(DOTEXE) -s $$? $$@  \
+	$(call endrule,stubsis)
+endef
+
+# Build stub SIS file
+SISFILE:= $(TARGETDIR)/$(SISNAME).sis
+# Here a variable named "done_<sanitised $SISFILE>" gets created
+GUARD:=done_$(call sanitise,$(SISFILE))
+# If variable "done_..." not set, set it to 1, so that
+# UREL and UDEB do not execute makesis twice on the same target 
+ifeq ($($(GUARD)),)
+$(GUARD):=1
+ALL:: $(SISFILE)
+$(eval $(call SisFileCreation))
+$(eval $(call whatmacro,$(SISFILE)))
+$(eval $(call GenerateStandardCleanTarget,$(SISFILE),$(TARGETDIR)))
+endif
+
+
--- a/sbsv2/raptor/lib/flm/tools/stlport.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/tools/stlport.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,139 +1,139 @@
-# 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:
-#
-
-# FLM to build STLport libraries.
-
-## Outputs - externally relevant targets that this FLM generates
-
-ifeq ($(OSTYPE),unix)
-STLPORT.OPT:=-fPIC -m32 -O2
-STLPORT.CXXFLAGS:=-m32 
-else
-STLPORT.OPT:=-O2
-STLPORT.CXXFLAGS:=
-endif
-
-
-SOURCE_ARCHIVE:=$(EXTENSION_ROOT)/$(SOURCE_ARCHIVE)
-
-EXTRACT_DIR:=$(EPOCBLD)$(TOOLPLATFORMDIR)
-STL_DIR:=$(EXTRACT_DIR)/STLport-$(STLPORT_VERSION)
-BUILD_DIR:=$(STL_DIR)/build/lib
-UNZIPPED:=$(STL_DIR)/unzipped.ok
-
-RELEASE_DIR:=$(EPOCROOT)/epoc32/release/tools2$(TOOLPLATFORMDIR)
-RELEASE_DIR_REL:=$(RELEASE_DIR)/rel
-RELEASE_DIR_DEB:=$(RELEASE_DIR)/deb
-WHATFLM:=
-
-ifeq ($(OSTYPE),unix)
-STLPORT.OPT:=-fPIC -m32 -O2
-STLPORT.CXXFLAGS:=-m32 
-else
-STLPORT.OPT:=-O2
-STLPORT.CXXFLAGS:=
-endif
-
-STL_REL_LIB_PATH:=$(STL_DIR)/lib/libstlport.a
-STL_DEB_LIB_PATH:=$(STL_DIR)/lib/libstlportg.a
-
-REL_LIB:=$(RELEASE_DIR_REL)/$(STL_REL_LIB_NAME)
-DEB_LIB:=$(RELEASE_DIR_DEB)/$(STL_REL_LIB_NAME)
-
-STL_HEADERS_PATH:=$(EPOCROOT)/epoc32/include/tools/stlport
-
-CLEANTARGETS:=
-CREATABLEPATHS:=
-
-define stlportcommon
-
-$(UNZIPPED): $(SOURCE_ARCHIVE) 
-	$(call startrule,unzip) \
-	$(UNZIP) -aa -o $(SOURCE_ARCHIVE) -d $(EXTRACT_DIR) && \
-	echo "SHELL:=$$$${SHELL}" > "$(BUILD_DIR)/raptor_gcc.mak" && \
-	$(GNUCAT) $(BUILD_DIR)/gcc.mak >> "$(BUILD_DIR)/raptor_gcc.mak" && \
-	$(GNUTOUCH) $(UNZIPPED) \
-	$(call endrule,unzip)
-
-CLEAN::
-	$(call startrule,clean) \
-	$(GNURM) -f $(UNZIPPED) ; \
-	$(GNURM) -rf $(STL_DIR)  \
-	$(call endrule,clean)
-
-CREATABLEPATHS:=$$(CREATABLEPATHS) $(dir $(UNZIPPED))
-endef
-
-# only declare targets once if they are the same for urel or udeb
-
-ifeq ($(TARGET_$(STL_DIR)),)
-$(eval $(stlportcommon))
-TARGET_$(STL_DIR):=1
-endif
-
-
-define stlportrel
-$(ALLTARGET):: $(REL_LIB)
-LIBRARY:: $(REL_LIB)
-
-$(REL_LIB): $(STL_REL_LIB_PATH)
-	$(call startrule,install) \
-	$(GNUCP) $(STL_REL_LIB_PATH) $(REL_LIB) \
-	$(call endrule,install)
-
-$(STL_REL_LIB_PATH): $(UNZIPPED)
-	$(call startrule,make) \
-	$(GNUMAKE38) -C "$(BUILD_DIR)" -fraptor_gcc.mak install-release-static LIB_SUFFIX= BASE_INSTALL_DIR=../.. EXTRA_CXXFLAGS='$(STLPORT.CXXFLAGS)' OPT='$(STLPORT.OPT)' \
-	$(call endrule,make)
-
-CREATABLEPATHS:=$$(CREATABLEPATHS) $(dir $(REL_LIB))
-CLEANTARGETS:=$$(CLEANTARGETS) $(REL_LIB)
-WHATFLM:=$$(WHATFLM) $(REL_LIB)
-endef
-
-ifeq ($(CFG_PATH),rel)
-$(eval $(stlportrel))
-endif
-
-define stlportdeb
-$(ALLTARGET):: $(DEB_LIB)
-LIBRARY:: $(DEB_LIB)
-
-$(DEB_LIB): $(STL_DEB_LIB_PATH)
-	$(call startrule,install) \
-	$(GNUCP) $(STL_DEB_LIB_PATH) $(DEB_LIB) \
-	$(call endrule,install)
-
-$(STL_DEB_LIB_PATH):  $(UNZIPPED)
-	$(call startrule,make) \
-	$(GNUMAKE38) -C "$(BUILD_DIR)" -fraptor_gcc.mak install-dbg-static LIB_SUFFIX= BASE_INSTALL_DIR=../.. EXTRA_CXXFLAGS='$(STLPORT.CXXFLAGS)' OPT='$(STLPORT.OPT)' \
-	$(call endrule,make)
-
-	
-CREATABLEPATHS:=$$(CREATABLE_PATHS) $(dir $(DEB_LIB))
-CLEANTARGETS:=$$(CLEANTARGETS) $(DEB_LIB)
-WHATFLM:=$$(WHATFLM) $(DEB_LIB)
-endef
-
-ifeq ($(CFG_PATH),deb)
-$(eval $(stlportdeb))
-endif
-
-$(eval $(call whatmacro,$(WHATFLM),WHATTEM))
-# make the output directories while reading makefile - some build engines prefer this
-$(call makepath,$(CREATABLEPATHS))
-
-## Clean up (using eval to avoid target specific variables)
-$(eval $(call GenerateStandardCleanTarget,$(CLEANTARGETS),))
+# 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:
+#
+
+# FLM to build STLport libraries.
+
+## Outputs - externally relevant targets that this FLM generates
+
+ifeq ($(OSTYPE),unix)
+STLPORT.OPT:=-fPIC -m32 -O2
+STLPORT.CXXFLAGS:=-m32 
+else
+STLPORT.OPT:=-O2
+STLPORT.CXXFLAGS:=
+endif
+
+
+SOURCE_ARCHIVE:=$(EXTENSION_ROOT)/$(SOURCE_ARCHIVE)
+
+EXTRACT_DIR:=$(EPOCBLD)$(TOOLPLATFORMDIR)
+STL_DIR:=$(EXTRACT_DIR)/STLport-$(STLPORT_VERSION)
+BUILD_DIR:=$(STL_DIR)/build/lib
+UNZIPPED:=$(STL_DIR)/unzipped.ok
+
+RELEASE_DIR:=$(EPOCROOT)/epoc32/release/tools2$(TOOLPLATFORMDIR)
+RELEASE_DIR_REL:=$(RELEASE_DIR)/rel
+RELEASE_DIR_DEB:=$(RELEASE_DIR)/deb
+WHATFLM:=
+
+ifeq ($(OSTYPE),unix)
+STLPORT.OPT:=-fPIC -m32 -O2
+STLPORT.CXXFLAGS:=-m32 
+else
+STLPORT.OPT:=-O2
+STLPORT.CXXFLAGS:=
+endif
+
+STL_REL_LIB_PATH:=$(STL_DIR)/lib/libstlport.a
+STL_DEB_LIB_PATH:=$(STL_DIR)/lib/libstlportg.a
+
+REL_LIB:=$(RELEASE_DIR_REL)/$(STL_REL_LIB_NAME)
+DEB_LIB:=$(RELEASE_DIR_DEB)/$(STL_REL_LIB_NAME)
+
+STL_HEADERS_PATH:=$(EPOCROOT)/epoc32/include/tools/stlport
+
+CLEANTARGETS:=
+CREATABLEPATHS:=
+
+define stlportcommon
+
+$(UNZIPPED): $(SOURCE_ARCHIVE) 
+	$(call startrule,unzip) \
+	$(UNZIP) -aa -o $(SOURCE_ARCHIVE) -d $(EXTRACT_DIR) && \
+	echo "SHELL:=$$$${SHELL}" > "$(BUILD_DIR)/raptor_gcc.mak" && \
+	$(GNUCAT) $(BUILD_DIR)/gcc.mak >> "$(BUILD_DIR)/raptor_gcc.mak" && \
+	$(GNUTOUCH) $(UNZIPPED) \
+	$(call endrule,unzip)
+
+CLEAN::
+	$(call startrule,clean) \
+	$(GNURM) -f $(UNZIPPED) ; \
+	$(GNURM) -rf $(STL_DIR)  \
+	$(call endrule,clean)
+
+CREATABLEPATHS:=$$(CREATABLEPATHS) $(dir $(UNZIPPED))
+endef
+
+# only declare targets once if they are the same for urel or udeb
+
+ifeq ($(TARGET_$(STL_DIR)),)
+$(eval $(stlportcommon))
+TARGET_$(STL_DIR):=1
+endif
+
+
+define stlportrel
+$(ALLTARGET):: $(REL_LIB)
+LIBRARY:: $(REL_LIB)
+
+$(REL_LIB): $(STL_REL_LIB_PATH)
+	$(call startrule,install) \
+	$(GNUCP) $(STL_REL_LIB_PATH) $(REL_LIB) \
+	$(call endrule,install)
+
+$(STL_REL_LIB_PATH): $(UNZIPPED)
+	$(call startrule,make) \
+	$(GNUMAKE38) -C "$(BUILD_DIR)" -fraptor_gcc.mak install-release-static LIB_SUFFIX= BASE_INSTALL_DIR=../.. EXTRA_CXXFLAGS='$(STLPORT.CXXFLAGS)' OPT='$(STLPORT.OPT)' \
+	$(call endrule,make)
+
+CREATABLEPATHS:=$$(CREATABLEPATHS) $(dir $(REL_LIB))
+CLEANTARGETS:=$$(CLEANTARGETS) $(REL_LIB)
+WHATFLM:=$$(WHATFLM) $(REL_LIB)
+endef
+
+ifeq ($(CFG_PATH),rel)
+$(eval $(stlportrel))
+endif
+
+define stlportdeb
+$(ALLTARGET):: $(DEB_LIB)
+LIBRARY:: $(DEB_LIB)
+
+$(DEB_LIB): $(STL_DEB_LIB_PATH)
+	$(call startrule,install) \
+	$(GNUCP) $(STL_DEB_LIB_PATH) $(DEB_LIB) \
+	$(call endrule,install)
+
+$(STL_DEB_LIB_PATH):  $(UNZIPPED)
+	$(call startrule,make) \
+	$(GNUMAKE38) -C "$(BUILD_DIR)" -fraptor_gcc.mak install-dbg-static LIB_SUFFIX= BASE_INSTALL_DIR=../.. EXTRA_CXXFLAGS='$(STLPORT.CXXFLAGS)' OPT='$(STLPORT.OPT)' \
+	$(call endrule,make)
+
+	
+CREATABLEPATHS:=$$(CREATABLE_PATHS) $(dir $(DEB_LIB))
+CLEANTARGETS:=$$(CLEANTARGETS) $(DEB_LIB)
+WHATFLM:=$$(WHATFLM) $(DEB_LIB)
+endef
+
+ifeq ($(CFG_PATH),deb)
+$(eval $(stlportdeb))
+endif
+
+$(eval $(call whatmacro,$(WHATFLM),WHATTEM))
+# make the output directories while reading makefile - some build engines prefer this
+$(call makepath,$(CREATABLEPATHS))
+
+## Clean up (using eval to avoid target specific variables)
+$(eval $(call GenerateStandardCleanTarget,$(CLEANTARGETS),))
--- a/sbsv2/raptor/lib/flm/tools/test_command_diff.sh	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/tools/test_command_diff.sh	Wed Jun 23 16:56:47 2010 +0800
@@ -1,5 +1,5 @@
-#!/bin/bash
-
-# Example of how to compare two invocations of a tool
-( echo 'armcc    -O2 --dllimport_runtime --exceptions --exceptions_unwind --diag_suppress 161,611,654,997,1152,1300,1464,1488,6318 --diag_error 1267 --cpu 5T  --enum_is_int -Ono_known_library --fpmode ieee_no_fenv --export_all_vtbl --no_vfe --apcs /inter -c   --thumb  --fpu softvfp  -D__MARM_THUMB__  -D__MARM_INTERWORK__   -DNDEBUG -D_UNICODE   -D__SYMBIAN32__ -D__ARMCC__ -D__EPOC32__ -D__MARM__ -D__EABI__ -D__ARMCC_2__ -D__ARMCC_2_2__ -D__MARM_ARMV5__ -D__EXE__ -D__SUPPORT_CPP_EXCEPTIONS__   -D__PRODUCT_INCLUDE__=\"/epoc32/include/variant/Symbian_OS_vFuture.hrh\"    --cpp --preinclude \EPOC32\INCLUDE\RVCT2_2\RVCT2_2.h -J\comms-infras\commsdat\Tools\ced\src -J\comms-infras\commsdat\Tools\ced\inc -J\EPOC32\include -J\epoc32\include\variant -o \EPOC32\BUILD\comms-infras\commsdat\group\CED\ARMV5\UREL\database.o \comms-infras\commsdat\Tools\ced\src\database.cpp filedump.cpp';
-echo 'armcc  -g --dwarf3  -O0 --dllimport_runtime --exceptions --exceptions_unwind --diag_suppress 161,611,654,997,1152,1300,1464,1488,6318 --diag_error 1267 --cpu 5T  --enum_is_int -Ono_known_library --fpmode ieee_no_fenv --export_all_vtbl --no_vfe --apcs /inter   -c   --thumb  --fpu softvfp  -D__MARM_THUMB__  -D__MARM_INTERWORK__   -D_DEBUG -D_UNICODE   -D__SYMBIAN32__ -D__ARMCC__ -D__EPOC32__ -D__MARM__ -D__EABI__ -D__ARMCC_2__ -D__ARMCC_2_2__ -D__MARM_ARMV5__ -D__EXE__ -D__SUPPORT_CPP_EXCEPTIONS__   -D__PRODUCT_INCLUDE__=\"/epoc32/include/variant/Symbian_OS_vFuture.hrh\"    --cpp --preinclude \EPOC32\INCLUDE\RVCT2_2\RVCT2_2.h  -J\comms-infras\commsdat\Tools\ceddump\src -J\comms-infras\commsdat\Tools\ceddump\inc  -J\comms-infras\commsdat\Tools\ced\inc -J\EPOC32\include -J\epoc32\include\variant -o \EPOC32\BUILD\comms-infras\commsdat\group\CEDDUMP\ARMV5\UDEB\mainentry.o \comms-infras\commsdat\Tools\ceddump\src\mainentry.cpp r99qosconversion.cpp') | python command_diff.py
+#!/bin/bash
+
+# Example of how to compare two invocations of a tool
+( echo 'armcc    -O2 --dllimport_runtime --exceptions --exceptions_unwind --diag_suppress 161,611,654,997,1152,1300,1464,1488,6318 --diag_error 1267 --cpu 5T  --enum_is_int -Ono_known_library --fpmode ieee_no_fenv --export_all_vtbl --no_vfe --apcs /inter -c   --thumb  --fpu softvfp  -D__MARM_THUMB__  -D__MARM_INTERWORK__   -DNDEBUG -D_UNICODE   -D__SYMBIAN32__ -D__ARMCC__ -D__EPOC32__ -D__MARM__ -D__EABI__ -D__ARMCC_2__ -D__ARMCC_2_2__ -D__MARM_ARMV5__ -D__EXE__ -D__SUPPORT_CPP_EXCEPTIONS__   -D__PRODUCT_INCLUDE__=\"/epoc32/include/variant/Symbian_OS_vFuture.hrh\"    --cpp --preinclude \EPOC32\INCLUDE\RVCT2_2\RVCT2_2.h -J\comms-infras\commsdat\Tools\ced\src -J\comms-infras\commsdat\Tools\ced\inc -J\EPOC32\include -J\epoc32\include\variant -o \EPOC32\BUILD\comms-infras\commsdat\group\CED\ARMV5\UREL\database.o \comms-infras\commsdat\Tools\ced\src\database.cpp filedump.cpp';
+echo 'armcc  -g --dwarf3  -O0 --dllimport_runtime --exceptions --exceptions_unwind --diag_suppress 161,611,654,997,1152,1300,1464,1488,6318 --diag_error 1267 --cpu 5T  --enum_is_int -Ono_known_library --fpmode ieee_no_fenv --export_all_vtbl --no_vfe --apcs /inter   -c   --thumb  --fpu softvfp  -D__MARM_THUMB__  -D__MARM_INTERWORK__   -D_DEBUG -D_UNICODE   -D__SYMBIAN32__ -D__ARMCC__ -D__EPOC32__ -D__MARM__ -D__EABI__ -D__ARMCC_2__ -D__ARMCC_2_2__ -D__MARM_ARMV5__ -D__EXE__ -D__SUPPORT_CPP_EXCEPTIONS__   -D__PRODUCT_INCLUDE__=\"/epoc32/include/variant/Symbian_OS_vFuture.hrh\"    --cpp --preinclude \EPOC32\INCLUDE\RVCT2_2\RVCT2_2.h  -J\comms-infras\commsdat\Tools\ceddump\src -J\comms-infras\commsdat\Tools\ceddump\inc  -J\comms-infras\commsdat\Tools\ced\inc -J\EPOC32\include -J\epoc32\include\variant -o \EPOC32\BUILD\comms-infras\commsdat\group\CEDDUMP\ARMV5\UDEB\mainentry.o \comms-infras\commsdat\Tools\ceddump\src\mainentry.cpp r99qosconversion.cpp') | python command_diff.py
--- a/sbsv2/raptor/lib/flm/tools2common.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/tools2common.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,107 +1,123 @@
-# 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:
-# Function-Like Makefile to build common TOOLS2 objects with gcc
-# (included by tools2exe.flm and tools2lib.flm)
-#
-#
-
-## Input parameters
-
-OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)_$(TARGETTYPE)/tools2/$(VARIANTTYPE)$(TOOLPLATFORMDIR)
-
-ifeq ($(OSTYPE),cygwin)
-CDEFS.TOOLS2:=$(CDEFS.WIN32) $(CDEFS)
-CFLAGS:=$(CFLAGS.WIN32) $(CFLAGS) $(OPTION_GCC)
-COMPILER_PATH:=$(COMPILER_PATH.WIN32)
-else
-CDEFS.TOOLS2:=$(CDEFS.LINUX) $(CDEFS)
-CFLAGS:=$(CFLAGS) $(OPTION_GCC)
-COMPILER_PATH=$(COMPILER_PATH.LINUX)
-endif
-CDEFS.TOOLS2:=$(call makemacrodef,$(OPT.D),$(CDEFS.TOOLS2))
-
-## Locally used variables
-CREATABLEPATHS:=$(OUTPUTPATH) $(RELEASEPATH) $(TOOLSPATH)
-
-## Global targets
-$(ALLTARGET):: $(TARGETS)
-TARGET:: $(TARGETS)
-
-## Pre-Include directories
-ifneq ($(INC.COMPILER),)
-PINCLUDE:=$(patsubst %,$(OPT.PREINCLUDE)%,$(INC.COMPILER))
-endif
-
-## User and System Include directories
-ifneq ($(USERINCLUDE),)
-UINCLUDE:=$(patsubst %,$(OPT.USERINCLUDE)%,$(USERINCLUDE))
-endif
-ifneq ($(SYSTEMINCLUDE),)
-SINCLUDE:=$(patsubst %,$(OPT.SYSTEMINCLUDE)%,$(SYSTEMINCLUDE))
-endif
-
-INCLUDES:=$(PINCLUDE) $(UINCLUDE) $(SINCLUDE)
-
-## Source files
-CPPFILES:=$(filter %.CPP,$(SOURCE))
-cppFILES:=$(filter %.cpp,$(SOURCE))
-CFILES:=$(filter %.C,$(SOURCE))
-cFILES:=$(filter %.c,$(SOURCE))
-
-## Object files
-CPPOBJFILES:=$(patsubst %,$(OUTPUTPATH)/%,$(notdir $(patsubst %.CPP,%.o,$(CPPFILES))))
-cppOBJFILES:=$(patsubst %,$(OUTPUTPATH)/%,$(notdir $(patsubst %.cpp,%.o,$(cppFILES))))
-COBJFILES:=$(patsubst %,$(OUTPUTPATH)/%,$(notdir $(patsubst %.C,%.o,$(CFILES))))
-cOBJFILES:=$(patsubst %,$(OUTPUTPATH)/%,$(notdir $(patsubst %.c,%.o,$(cFILES))))
-OBJECTFILES:=$(CPPOBJFILES) $(cppOBJFILES) $(cOBJFILES) $(COBJFILES)
-
-CLEANTARGETS:=
-## Compile CPP and cpp files
-define compile2object
-$(eval compile2object_TARGET:=$(OUTPUTPATH)/$(patsubst %.$(2),%.o,$(notdir $(1))))
-$(eval DEPENDFILENAME:=$(compile2object_TARGET).d)
-$(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
-$(compile2object_TARGET): $(1) $(if (DEPENDFILE),,EXPORT)
-	$(call startrule,compile2object,,$(1)) \
-	$(if $(COMPILER_PATH),COMPILER_PATH="$(COMPILER_PATH)",) \
-	$(COMPILER) $(CFLAGS) $(CDEFS.TOOLS2) -MD -MT"$$@" -MF"$(DEPENDFILENAME)" $(INCLUDES) $(OPT.O)"$$@" "$(1)" \
-	$(call endrule,compile2object)
-
-CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
-ifneq "$(DEPENDFILE)" ""
-ifeq ($(NO_DEPEND_INCLUDE),)
-  ifeq "$(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS)))" ""
-    -include $(DEPENDFILE)
-  endif
-endif
-endif
-
-endef
-
-$(foreach SRC,$(CPPFILES),$(eval $(call compile2object,$(SRC),CPP)))
-$(foreach SRC,$(cppFILES),$(eval $(call compile2object,$(SRC),cpp)))
-$(foreach SRC,$(CFILES),$(eval $(call compile2object,$(SRC),C)))
-$(foreach SRC,$(cFILES),$(eval $(call compile2object,$(SRC),c)))
-
-### Conclusion - cleanup and introspection #######################
-
-# make the output directories while reading makefile - some build engines prefer this
-$(call makepath,$(CREATABLEPATHS))
-
-## Clean up (using eval to avoid target specific variables)
-$(eval $(call GenerateStandardCleanTarget,$(TARGETS) $(OBJECTFILES),$(CREATABLEPATHS),))
-## WHAT target
-$(eval $(call whatmacro,$(RELEASEABLES),WHATTOOLS2))
-
-## The End
+# 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:
+# Function-Like Makefile to build common TOOLS2 objects with gcc
+# (included by tools2exe.flm and tools2lib.flm)
+#
+#
+
+## Input parameters
+
+ifeq ($(filter win,$(HOSTPLATFORM)),win)
+CDEFS.TOOLS2:=$(CDEFS.WIN32) $(CDEFS)
+CFLAGS:=$(CFLAGS.WIN32) $(CFLAGS) $(OPTION_GCC)
+COMPILER_PATH:=$(COMPILER_PATH.WIN32)
+OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)_$(TARGETTYPE)/tools2/$(VARIANTTYPE)$(TOOLPLATFORMDIR)
+else
+ifneq ($(TOOLS2WIN32),)
+# Build win32 tools in Linux
+CDEFS.TOOLS2:=$(CDEFS.WIN32) $(CDEFS)
+CFLAGS:=$(CFLAGS.WIN32) $(CFLAGS) $(OPTION_GCC)
+COMPILER_PATH:=$(COMPILER_PATH.WIN32)
+OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)_$(TARGETTYPE)/tools2/$(VARIANTTYPE)
+else
+# Build linux tools in Linux
+CDEFS.TOOLS2:=$(CDEFS.LINUX) $(CDEFS)
+CFLAGS:=$(CFLAGS) $(OPTION_GCC)
+COMPILER_PATH=$(COMPILER_PATH.LINUX)
+OUTPUTPATH:=$(OUTPUTPATH)/$(TARGET)_$(TARGETTYPE)/tools2/$(VARIANTTYPE)$(TOOLPLATFORMDIR)
+endif
+endif
+
+
+CDEFS.TOOLS2:=$(call makemacrodef,$(OPT.D),$(CDEFS.TOOLS2))
+
+## Locally used variables
+CREATABLEPATHS:=$(OUTPUTPATH) $(RELEASEPATH) $(TOOLSPATH)
+
+## Global targets
+$(ALLTARGET):: $(TARGETS)
+TARGET:: $(TARGETS)
+
+## Pre-Include directories
+ifneq ($(INC.COMPILER),)
+PINCLUDE:=$(patsubst %,$(OPT.PREINCLUDE)%,$(INC.COMPILER))
+endif
+
+## User and System Include directories
+ifneq ($(USERINCLUDE),)
+UINCLUDE:=$(patsubst %,$(OPT.USERINCLUDE)%,$(USERINCLUDE))
+endif
+ifneq ($(SYSTEMINCLUDE),)
+SINCLUDE:=$(patsubst %,$(OPT.SYSTEMINCLUDE)%,$(SYSTEMINCLUDE))
+endif
+
+INCLUDES:=$(PINCLUDE) $(UINCLUDE) $(SINCLUDE)
+
+## Source files
+CPPFILES:=$(filter %.CPP,$(SOURCE))
+cppFILES:=$(filter %.cpp,$(SOURCE))
+CFILES:=$(filter %.C,$(SOURCE))
+cFILES:=$(filter %.c,$(SOURCE))
+
+## Object files
+CPPOBJFILES:=$(patsubst %,$(OUTPUTPATH)/%,$(notdir $(patsubst %.CPP,%.o,$(CPPFILES))))
+cppOBJFILES:=$(patsubst %,$(OUTPUTPATH)/%,$(notdir $(patsubst %.cpp,%.o,$(cppFILES))))
+COBJFILES:=$(patsubst %,$(OUTPUTPATH)/%,$(notdir $(patsubst %.C,%.o,$(CFILES))))
+cOBJFILES:=$(patsubst %,$(OUTPUTPATH)/%,$(notdir $(patsubst %.c,%.o,$(cFILES))))
+OBJECTFILES:=$(CPPOBJFILES) $(cppOBJFILES) $(cOBJFILES) $(COBJFILES)
+
+CLEANTARGETS:=
+## Compile CPP and cpp files
+define compile2object
+$(eval compile2object_TARGET:=$(OUTPUTPATH)/$(patsubst %.$(2),%.o,$(notdir $(1))))
+$(eval DEPENDFILENAME:=$(compile2object_TARGET).d)
+$(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
+$(compile2object_TARGET): $(1) $(if (DEPENDFILE),,EXPORT)
+	$(call startrule,compile2object,,$(1)) \
+	$(if $(COMPILER_PATH),COMPILER_PATH="$(COMPILER_PATH)",) \
+	$(COMPILER) $(CFLAGS) $(CDEFS.TOOLS2) \
+	$(if $(NO_DEPEND_GENERATE),,-MD -MT"$$@" -MF"$(DEPENDFILENAME)") \
+	$(INCLUDES) $(OPT.O)"$$@" "$(1)" \
+	$(call endrule,compile2object)
+
+ifeq ($(NO_DEPEND_GENERATE),)
+  CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
+endif
+
+ifneq ($(DEPENDFILE),)
+  ifeq ($(NO_DEPEND_INCLUDE),)
+    ifeq ($(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS))),)
+      -include $(DEPENDFILE)
+    endif
+  endif
+endif
+
+endef
+
+$(foreach SRC,$(CPPFILES),$(eval $(call compile2object,$(SRC),CPP)))
+$(foreach SRC,$(cppFILES),$(eval $(call compile2object,$(SRC),cpp)))
+$(foreach SRC,$(CFILES),$(eval $(call compile2object,$(SRC),C)))
+$(foreach SRC,$(cFILES),$(eval $(call compile2object,$(SRC),c)))
+
+### Conclusion - cleanup and introspection #######################
+
+# make the output directories while reading makefile - some build engines prefer this
+$(call makepath,$(CREATABLEPATHS))
+
+## Clean up
+$(call raptor_clean,$(CLEANTARGETS) $(OBJECTFILES))
+## for the --what option and the log file
+$(call raptor_release,$(RELEASABLES))
+
+## The End
--- a/sbsv2/raptor/lib/flm/tools2exe.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/tools2exe.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,77 +1,85 @@
-# 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:
-# Function-Like Makefile to build a TOOLS2 EXE with gcc
-# 
-#
-
-## Outputs - externally relevant targets that this FLM generates
-ifeq ($(OSTYPE),cygwin)
-SYSTEMLIBS:=$(LIBS.WIN32)
-else
-SYSTEMLIBS:=$(LIBS.LINUX)
-endif
-
-EXETARGET:=$(RELEASEPATH)/$(TARGET)$(DOTEXE)
-
-ifneq ($(TOOLSPATH),)
-INSTALLED:=$(TOOLSPATH)/$(TARGET)$(DOTEXE)
-endif
-
-## Target groups
-RELEASEABLES:=$(INSTALLED)
-TARGETS:=$(EXETARGET) $(INSTALLED)
-
-## Common build steps (compiling and cleaning)
-include $(FLMHOME)/tools2common.flm
-
-## Static libraries
-ifneq ($(STATICLIBRARY),)
-STATICLIBS:=$(patsubst %,$(RELEASEPATH)/lib%.a,$(STATICLIBRARY))
-LLIBS:=$(OPT.L)"$(RELEASEPATH)" $(patsubst %,$(OPT.l)%,$(STATICLIBRARY))
-#
-ifneq ($(SYSTEMLIBS),)
-LLIBS:=$(LLIBS) $(patsubst %,$(OPT.l)%,$(SYSTEMLIBS))
-endif
-#
-endif
-
-## Link executable
-# get OBJECTFILES from call to tools2common
-define tools2linkexe
-$(EXETARGET): $(OBJECTFILES) $(STATICLIBS)
-	$(call startrule,tools2linkexe) \
-	$(LINKER) $(CFLAGS) $(LFLAGS) $(OPT.O)"$(EXETARGET)" $(call dblquote,$(OBJECTFILES)) $(LLIBS) \
-	$(if $(SAVESPACE),; $(GNURM) -rf $(OUTPUTPATH); true,) \
-	$(call endrule,tools2linkexe)
-
-endef
-
-$(eval $(call tools2linkexe))
-
-	
-## Copy executable to the tools directory
-ifneq ($(TOOLSPATH),)
-define tools2install
-$(INSTALLED): $(EXETARGET)
-	$(call startrule,tools2install) \
-	$(GNUCP) "$(EXETARGET)" "$(INSTALLED)" && \
-	$(GNUCHMOD) a+rwx "$(INSTALLED)" \
-	$(call endrule,tools2install)
-endef
-
-$(eval $(call tools2install))
-
-endif
-
-## The End
+# 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:
+# Function-Like Makefile to build a TOOLS2 EXE with gcc
+# 
+#
+
+## Outputs - externally relevant targets that this FLM generates
+ifeq ($(filter win,$(HOSTPLATFORM)),win)
+SYSTEMLIBS:=$(LIBS.WIN32)
+else
+ifneq ($(TOOLS2WIN32),)
+# Build win32 tools in Linux 
+SYSTEMLIBS:=$(LIBS.WIN32)
+else
+# Build linux tools in Linux
+SYSTEMLIBS:=$(LIBS.LINUX)
+endif
+endif
+
+
+EXETARGET:=$(RELEASEPATH)/$(TARGET)$(DOTEXE)
+
+INSTALLED:=
+ifneq ($(TOOLSPATH),)
+INSTALLED:=$(TOOLSPATH)/$(TARGET)$(DOTEXE)
+endif
+
+## Target groups
+RELEASABLES:=$(INSTALLED)
+TARGETS:=$(EXETARGET) $(INSTALLED)
+
+## Common build steps (compiling and cleaning)
+include $(FLMHOME)/tools2common.flm
+
+## Static libraries
+ifneq ($(STATICLIBRARY),)
+STATICLIBS:=$(patsubst %,$(RELEASEPATH)/lib%.a,$(STATICLIBRARY))
+LLIBS:=$(OPT.L)"$(RELEASEPATH)" $(patsubst %,$(OPT.l)%,$(STATICLIBRARY))
+#
+ifneq ($(SYSTEMLIBS),)
+LLIBS:=$(LLIBS) $(patsubst %,$(OPT.l)%,$(SYSTEMLIBS))
+endif
+#
+endif
+
+## Link executable
+# get OBJECTFILES from call to tools2common
+define tools2linkexe
+$(EXETARGET): $(OBJECTFILES) $(STATICLIBS)
+	$(call startrule,tools2linkexe) \
+	$(LINKER) $(CFLAGS) $(LFLAGS) $(OPT.O)"$(EXETARGET)" $(call dblquote,$(OBJECTFILES)) $(LLIBS) $(LINKER_OPTIONS) \
+	$(if $(SAVESPACE),; $(GNURM) -rf $(OUTPUTPATH); true,) \
+	$(call endrule,tools2linkexe)
+
+endef
+
+$(eval $(call tools2linkexe))
+
+	
+## Copy executable to the tools directory
+ifneq ($(TOOLSPATH),)
+define tools2install
+$(INSTALLED): $(EXETARGET)
+	$(call startrule,tools2install) \
+	$(GNUCP) "$(EXETARGET)" "$(INSTALLED)" && \
+	$(GNUCHMOD) a+rwx "$(INSTALLED)" \
+	$(call endrule,tools2install)
+endef
+
+$(eval $(call tools2install))
+
+endif
+
+## The End
--- a/sbsv2/raptor/lib/flm/tools2lib.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/tools2lib.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,45 +1,45 @@
-# 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:
-# Function-Like Makefile to build a TOOLS2 LIB with gcc
-# 
-#
-
-## Outputs - externally relevant targets that this FLM generates
-LIBTARGET:=$(RELEASEPATH)/$(TARGET).a
-
-## Target groups
-RELEASEABLES:=$(LIBTARGET)
-TARGETS:=$(LIBTARGET)
-
-## Common build steps (compiling)
-include $(FLMHOME)/tools2common.flm
-
-## Create library archive
-# get OBJECTFILES from tools2common
-define tools2lib
-$(LIBTARGET): $(OBJECTFILES)
-	$(call startrule,tools2lib) \
-	$(ARCHIVER) $(AFLAGS) $(LIBTARGET) $(OBJECTFILES) && \
-	$(RANLIB) $(LIBTARGET) \
-	$(if $(SAVESPACE),; $(GNURM) -rf $(OUTPUTPATH); true,) \
-	$(call endrule,tools2lib)
-
-endef
-
-$(eval $(call tools2lib))
-
-## Global target
-LIBRARY:: $(LIBTARGET)
-
-## The End
+# 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:
+# Function-Like Makefile to build a TOOLS2 LIB with gcc
+# 
+#
+
+## Outputs - externally relevant targets that this FLM generates
+LIBTARGET:=$(RELEASEPATH)/$(TARGET).a
+
+## Target groups
+RELEASABLES:=$(LIBTARGET)
+TARGETS:=$(LIBTARGET)
+
+## Common build steps (compiling)
+include $(FLMHOME)/tools2common.flm
+
+## Create library archive
+# get OBJECTFILES from tools2common
+define tools2lib
+$(LIBTARGET): $(OBJECTFILES)
+	$(call startrule,tools2lib) \
+	$(ARCHIVER) $(AFLAGS) $(LIBTARGET) $(OBJECTFILES) && \
+	$(RANLIB) $(LIBTARGET) \
+	$(if $(SAVESPACE),; $(GNURM) -rf $(OUTPUTPATH); true,) \
+	$(call endrule,tools2lib)
+
+endef
+
+$(eval $(call tools2lib))
+
+## Global target
+LIBRARY:: $(LIBTARGET)
+
+## The End
--- a/sbsv2/raptor/lib/flm/tracecompiler.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/tracecompiler.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,76 +1,180 @@
-#
-# 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: 
-# Run Trace Compiler on source files to generate trace headers and decode files
-#
-
-TRACE_PRJNAME:=$(basename $(notdir $(PROJECT_META)))
-# Find out TRACE_PATH
-TRACE_PATH:=$(strip $(foreach DIR,$(USERINCLUDE),$(filter %/traces_$(TRACE_PRJNAME),$(DIR))))
-ifeq ($(TRACE_PATH),)
-TRACE_PATH:=$(strip $(foreach DIR,$(USERINCLUDE),$(filter %/traces,$(DIR))))
-endif
-
-# Run trace compiler only if TRACE_PATH exists
-ifneq ($(TRACE_PATH),)
-TRACE_MARKER:=$(TRACE_MARKER_PATH)/tracecompile_$(TRACE_PRJNAME)_$(UID_TC).done
-TRACE_HEADERS:=
-
-TRACE_SOURCE_LIST:=$(TRACE_MARKER_PATH)/tracecompile_$(TRACE_PRJNAME)_$(UID_TC).sourcelist
-
-# 1. Append to or create the list of source files for trace compiler to process
-# 2. Check if the hash in trace marker remain unchanged. If not, remove marker so trace compiler will run again. 
-X:=$(shell set -x ; $(GNUMKDIR) -p $(TRACE_MARKER_PATH) ; $(GNUTOUCH) $(TRACE_SOURCE_LIST) ; echo -e "$(subst $(CHAR_SPACE),\\n,$(SOURCE))" | $(GNUSORT) -u $(TRACE_SOURCE_LIST) - > $(TRACE_SOURCE_LIST).tmp && $(GNUMV) $(TRACE_SOURCE_LIST).tmp $(TRACE_SOURCE_LIST) ; $(GNUMD5SUM) -c $(TRACE_MARKER) || $(GNURM) $(TRACE_MARKER))
-
-$(if $(FLMDEBUG),$(info <debug>Trace Compiler sourcelist generation output: $(X)</debug>))
-
-$(TRACE_MARKER) : $(SOURCE)
-
-ifeq ($(GUARD_$(call sanitise,$(TRACE_MARKER))),)
-GUARD_$(call sanitise,$(TRACE_MARKER)):=1
-
-JAVA_COMMAND:=$(SBS_JAVATC)
-TRACE_COMPILER_PATH:=$(EPOCROOT)/epoc32/tools
-TRACE_COMPILER_START:=-classpath $(TRACE_COMPILER_PATH)/tracecompiler com.nokia.tracecompiler.TraceCompiler
-
-TRACE_HEADERS:=$(foreach SRC,$(SOURCE),$(TRACE_PATH)/$(basename $(notdir $(SRC)))Traces.h)
-
-# 1. Use pipe to send inputs to trace compiler to process
-# 2. Create a hash regarding to source names and put it in marker.
-# 3. Show source names that are processed by trace compiler
-define trace_compile
-$(TRACE_MARKER) : $(PROJECT_META)
-	$(call startrule,tracecompile) \
-	( echo -en "$(TRACE_PRJNAME)\n$(PROJECT_META)\n"; \
-	  $(GNUCAT) $(TRACE_SOURCE_LIST); \
-	  echo -en "*ENDOFSOURCEFILES*\n" ) | \
-	$(JAVA_COMMAND) $(TRACE_COMPILER_START) $(UID_TC) && \
-	$(GNUMD5SUM) $(TRACE_SOURCE_LIST) > $(TRACE_MARKER) ; \
-	$(GNUCAT) $(TRACE_SOURCE_LIST) \
-	$(call endrule,tracecompile)
-endef
-
-$(eval $(trace_compile))
-
-$(eval $(call GenerateStandardCleanTarget,$(TRACE_HEADERS) $(TRACE_PATH)/tracebuilder.cache $(TRACE_MARKER) $(TRACE_SOURCE_LIST),,))
-
-# End sanity guard
-endif
-
-else
-# Indicate to following parts of the FLM that we actually won't run
-# trace compiler so they can set dependencies accordingly.
-USE_TRACE_COMPILER:=
-endif
-
+# Copyright (c) 2009-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:
+# Run Trace Compiler on source files to generate trace headers and decode files
+
+# Expected inputs:
+# TARGETEXT
+
+# Set project name as <mmp_name>
+TRACE_PRJNAME:=$(basename $(notdir $(PROJECT_META)))
+OLDTC_TRACE_PRJNAME:=$(TRACE_PRJNAME)
+TRACE_RELEASABLE_ID:=$(TARGET)_$(TARGETEXT)
+
+define get_trace_path
+$(firstword $(filter %$1, $(USERINCLUDE) $(SYSTEMINCLUDE)))
+endef
+
+$(if $(FLMDEBUG),$(info <debug>INCLUDES=$(USERINCLUDE) $(SYSTEMINCLUDE)</debug>))
+$(if $(FLMDEBUG),$(info <debug>TARGET=$(TARGET) TARGETEXT=$(TARGETEXT)</debug>))
+
+# Find out TRACE_PATH  by looking for the trace folder in SYSTEMINCLUDE and USERINCLUDES
+# traces/traces_<target_name>_<target_extension>
+TRACE_PATH:=$(call get_trace_path,/traces/traces_$(TRACE_RELEASABLE_ID))
+ifneq ($(TRACE_PATH),)
+  TRACE_PRJNAME:=$(TRACE_RELEASABLE_ID)
+else # obsolete forms for compatibility
+  # traces_<target_name>_<target_ext>
+  TRACE_PATH:=$(call get_trace_path,/traces_$(TARGET)_$(TARGETEXT))
+  ifneq ($(TRACE_PATH),)
+    # set project name as <target_name>_<target_ext> instead of <mmp_name>
+    # to trick old TCom into finding the path.
+    OLDTC_TRACE_PRJNAME:=$(TARGET)_$(TARGETEXT)
+  else
+    # traces_<target_name>_<target_type>
+    TRACE_PATH:=$(call get_trace_path,/traces_$(TARGET)_$(TARGETTYPE))
+    ifneq ($(TRACE_PATH),)
+      # set project name as <target_name>_<target_type> instead of <mmp_name>
+      # to trick old TCom into finding the path.
+      OLDTC_TRACE_PRJNAME:=$(TARGET)_$(TARGETTYPE)
+    else
+      # traces_<mmp_name>
+      TRACE_PATH:=$(call get_trace_path,/traces_$(TRACE_PRJNAME))
+   
+      # traces
+      ifeq ($(TRACE_PATH),)
+       TRACE_PATH:=$(call get_trace_path,/traces)
+      endif
+    endif
+  endif
+endif
+
+
+# initialise (so what output will be correct if we don't actually run the TC)
+TRACE_DICTIONARY:=
+AUTOGEN_HEADER:=
+$(if $(FLMDEBUG),$(info <debug>TRACE_PATH='$(TRACE_PATH)'   TRACE_RELEASABLE_ID='$(TRACE_RELEASABLE_ID)'</debug>))
+
+# Run trace compiler only if TRACE_PATH exists
+ifneq ($(TRACE_PATH),)
+TRACE_MARKER:=$(TRACE_MARKER_PATH)/tracecompile_$(TRACE_RELEASABLE_ID)_$(UID_TC).done
+TRACE_HEADERS:=
+
+TRACE_SOURCE_LIST:=$(TRACE_MARKER_PATH)/tracecompile_$(TRACE_RELEASABLE_ID)_$(UID_TC).sourcelist
+
+# 1. Append to or create the list of source files for trace compiler to process
+# 2. Check if the hash in trace marker remain unchanged. If not, remove marker so trace compiler will run again. 
+X:=$(shell set -x ; $(GNUMKDIR) -p $(TRACE_MARKER_PATH) ; $(GNUTOUCH) $(TRACE_SOURCE_LIST) ; echo -e "$(subst $(CHAR_SPACE),\\n,$(SOURCE))" | $(GNUSORT) -u $(TRACE_SOURCE_LIST) - > $(TRACE_SOURCE_LIST).tmp && $(GNUMV) $(TRACE_SOURCE_LIST).tmp $(TRACE_SOURCE_LIST) ; $(GNUMD5SUM) -c $(TRACE_MARKER) || $(GNURM) $(TRACE_MARKER))
+
+$(if $(FLMDEBUG),$(info <debug>Trace Compiler sourcelist generation output: $(X)</debug>))
+
+$(TRACE_MARKER) : $(SOURCE)
+
+TRACE_HEADERS:=$(foreach SRC,$(SOURCE),$(TRACE_PATH)/$(basename $(notdir $(SRC)))Traces.h)
+
+$(TRACE_HEADERS): $(TRACE_MARKER)
+
+ifeq ($(GUARD_$(call sanitise,$(TRACE_MARKER))),)
+GUARD_$(call sanitise,$(TRACE_MARKER)):=1
+
+$(if $(FLMDEBUG),$(info <debug>PAST MARKER='$(TRACE_RELEASABLE_ID)'</debug>))
+# The trace compiler likes to change . into _ so we must do the same in the case of mmps with a name like
+# fred.prd.mmp we want fred_prd
+TRACE_PRJNAME_SANITISED:=$(subst .,_,$(TRACE_PRJNAME))
+OLDTC_TRACE_PRJNAME_SANITISED:=$(subst .,_,$(OLDTC_TRACE_PRJNAME))
+
+
+JAVA_COMMAND:=$(SBS_JAVATC)
+TRACE_COMPILER_PATH:=$(EPOCROOT)/epoc32/tools
+
+# declare the trace_compile macro but only do it once in the build
+ifeq ($(trace_compile),)
+
+# Find out which macro to declare - the one supporting the new CLI 
+# or the old one.  First try to find TraceCompilerMain.class 
+# If it is there then it might be the new posix-like interface
+TRACE_VER:=
+TRACE_VSTR:=
+
+TCClass:=$(wildcard  $(TRACE_COMPILER_PATH)/tracecompiler/com/nokia/tracecompiler/TraceCompilerMain.class)
+ifneq ($(TCClass),) 
+# Get the version string from the TC (assume it's the new one)
+TRACE_COMPILER_START:=-classpath $(TRACE_COMPILER_PATH)/tracecompiler com.nokia.tracecompiler.TraceCompilerMain
+TRACE_VSTR:=$(firstword $(subst TraceCompiler version ,,$(shell $(JAVA_COMMAND) $(TRACE_COMPILER_START) --version)))
+# check if it looks like a version that supports the new cli interface: supporting up to verion 9 in the future.
+TRACE_VER:=$(findstring new,$(foreach version,2 3 4 5 6 7 8 9,$(patsubst $(version).%,new,$(TRACE_VSTR))))
+endif
+$(if $(FLMDEBUG),$(info <debug>TRACE_VSTR=$(TRACE_VSTR) TRACE_VER=$(TRACE_VER)</debug>))
+
+ifeq ($(TRACE_VER),new)
+define trace_compile
+$(TRACE_MARKER) : $(PROJECT_META)
+	$(call startrule,tracecompile) \
+	( $(GNUCAT) $(TRACE_SOURCE_LIST); \
+	  echo -en "*ENDOFSOURCEFILES*\n" ) | \
+	$(JAVA_COMMAND) $(TRACE_COMPILER_START) $(if $(FLMDEBUG),-d,) --uid=$(UID_TC) --project=$(TRACE_PRJNAME) --mmp=$(PROJECT_META) --traces=$(TRACE_PATH) &&  \
+	$(GNUMD5SUM) $(TRACE_SOURCE_LIST) > $(TRACE_MARKER) && \
+	{ $(GNUTOUCH) $(TRACE_DICTIONARY) $(AUTOGEN_HEADER); \
+	 $(GNUCAT) $(TRACE_SOURCE_LIST) ; true ; } \
+	$(call endrule,tracecompile)
+endef
+
+else # Old inteface
+TRACE_COMPILER_START:=-classpath $(TRACE_COMPILER_PATH)/tracecompiler com.nokia.tracecompiler.TraceCompiler
+# 1. Use pipe to send inputs to trace compiler to process
+# 2. Create a hash regarding to source names and put it in marker.
+# 3. Show source names that are processed by trace compiler
+define trace_compile
+$(TRACE_MARKER) : $(PROJECT_META)
+	$(call startrule,tracecompile) \
+	( echo -en "$(OLDTC_TRACE_PRJNAME)\n$(PROJECT_META)\n"; \
+	  $(GNUCAT) $(TRACE_SOURCE_LIST); \
+	  echo -en "*ENDOFSOURCEFILES*\n" ) | \
+	$(JAVA_COMMAND) $(TRACE_COMPILER_START) $(UID_TC) &&  \
+	$(GNUMD5SUM) $(TRACE_SOURCE_LIST) > $(TRACE_MARKER) && \
+	{ $(GNUTOUCH) $(TRACE_DICTIONARY) $(AUTOGEN_HEADER); \
+	 $(GNUCAT) $(TRACE_SOURCE_LIST) ; true ; } \
+	$(call endrule,tracecompile)
+endef
+
+# End - new/old trace compiler
+endif
+
+# End - tracecompile is defined
+endif
+
+ifeq ($(TRACE_VER),new)
+TRACE_DICTIONARY:=$(EPOCROOT)/epoc32/ost_dictionaries/$(TRACE_PRJNAME_SANITISED)_0x$(UID_TC)_Dictionary.xml
+AUTOGEN_HEADER:=$(EPOCROOT)/epoc32/include/platform/symbiantraces/autogen/$(TRACE_PRJNAME_SANITISED)_0x$(UID_TC)_TraceDefinitions.h
+else
+TRACE_DICTIONARY:=$(EPOCROOT)/epoc32/ost_dictionaries/$(OLDTC_TRACE_PRJNAME_SANITISED)_0x$(UID_TC)_Dictionary.xml
+AUTOGEN_HEADER:=$(EPOCROOT)/epoc32/include/internal/symbiantraces/autogen/$(OLDTC_TRACE_PRJNAME_SANITISED)_0x$(UID_TC)_TraceDefinitions.h
+endif
+
+$(eval $(trace_compile))
+
+$(eval $(call GenerateStandardCleanTarget, $(TRACE_PATH)/tracebuilder.cache $(TRACE_MARKER) $(TRACE_SOURCE_LIST),,))
+
+$(call makepath,$(TRACE_PATH) $(dir $(TRACE_DICTIONARY) $(AUTOGEN_HEADER)))
+# End  - guard that prevents repeated calls to TCom
+endif
+
+$(eval $(call GenerateStandardCleanTarget,$(TRACE_HEADERS),,))
+
+# End - Nothing to trace (not trace path in include)
+else
+# Indicate to following parts of the FLM that we actually won't run
+# trace compiler so they can set dependencies accordingly.
+USE_TRACE_COMPILER:=
+endif
+
--- a/sbsv2/raptor/lib/flm/user/default.flm_ex	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/user/default.flm_ex	Wed Jun 23 16:56:47 2010 +0800
@@ -1,26 +1,26 @@
-# Copyright (c) Symbian Software Ltd 2008-2009.
-#
-# Description:
-# This is an example file.
-# If it exists, the file default.flm in this directory is automatically
-# included by $(SBS_HOME)/lib/flm/config/default.flm
-# This allows end-users to "drop in" a file which adds to the default
-# behaviour (or overrides it) rather than editing the shipped .flm file.
-# default.flm contains things which require one instance per configuration.
-# For example, dependencies in the epoc32 tree (which need the $(EPOCROOT)
-# variable) and recipes to make things not specified in a bld.inf file.
-#
-
-
-# an example dependency - the script my.pl uses the rcomp tool
-
-$(EPOCROOT)/epoc32/tools/my.pl:	$(EPOCROOT)/epoc32/tools/rcomp$(DOTEXE)
-
-
-# an example recipe - run an accounting script after the binaries are made
-
-FINAL::
-	python $(EPOCROOT)/epoc32/tools/my_account.py $(EPOCROOT) $(PLATFORM)
-
-
-# end of example file
+# Copyright (c) Symbian Software Ltd 2008-2009.
+#
+# Description:
+# This is an example file.
+# If it exists, the file default.flm in this directory is automatically
+# included by $(SBS_HOME)/lib/flm/config/default.flm
+# This allows end-users to "drop in" a file which adds to the default
+# behaviour (or overrides it) rather than editing the shipped .flm file.
+# default.flm contains things which require one instance per configuration.
+# For example, dependencies in the epoc32 tree (which need the $(EPOCROOT)
+# variable) and recipes to make things not specified in a bld.inf file.
+#
+
+
+# an example dependency - the script my.pl uses the rcomp tool
+
+$(EPOCROOT)/epoc32/tools/my.pl:	$(EPOCROOT)/epoc32/tools/rcomp$(DOTEXE)
+
+
+# an example recipe - run an accounting script after the binaries are made
+
+FINAL::
+	python $(EPOCROOT)/epoc32/tools/my_account.py $(EPOCROOT) $(PLATFORM)
+
+
+# end of example file
--- a/sbsv2/raptor/lib/flm/user/globals.mk_ex	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/user/globals.mk_ex	Wed Jun 23 16:56:47 2010 +0800
@@ -1,21 +1,21 @@
-# Copyright (c) Symbian Software Ltd 2008-2009.
-#
-# Description:
-# This is an example file.
-# If it exists, the file globals.mk in this directory is automatically
-# included by $(SBS_HOME)/lib/flm/globals.mk
-# This allows end-users to "drop in" a file which adds to the default
-# behaviour (or overrides it) rather than editing the shipped .mk file.
-# globals.mk contains things which require one instance per build.
-# For example, macros and variables, dependencies and targets which are
-# truly global - independent of the epoc32 tree location.
-#
-
-
-# example resource dependency variables
-
-mycore_DEPENDS:=eikcore.rsg eikcoctl.rsg
-mymisc_DEPENDS:=eikmisc.rsg
-
-
-# end of example file
+# Copyright (c) Symbian Software Ltd 2008-2009.
+#
+# Description:
+# This is an example file.
+# If it exists, the file globals.mk in this directory is automatically
+# included by $(SBS_HOME)/lib/flm/globals.mk
+# This allows end-users to "drop in" a file which adds to the default
+# behaviour (or overrides it) rather than editing the shipped .mk file.
+# globals.mk contains things which require one instance per build.
+# For example, macros and variables, dependencies and targets which are
+# truly global - independent of the epoc32 tree location.
+#
+
+
+# example resource dependency variables
+
+mycore_DEPENDS:=eikcore.rsg eikcoctl.rsg
+mymisc_DEPENDS:=eikmisc.rsg
+
+
+# end of example file
--- a/sbsv2/raptor/lib/flm/utils/copydir.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/utils/copydir.flm	Wed Jun 23 16:56:47 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:
-#
-
-# FLM to recursively copy one directory into another.
-
-# parameters
-#
-# SOURCE_DIR	the source directory, relative to EXTENSION_ROOT
-# DEST_DIR		the destination directory, relative to EPOCROOT
-
-SOURCEPATH:=$(EXTENSION_ROOT)/$(SOURCE_DIR)
-DESTPATH:=$(EPOCROOT)/$(DEST_DIR)
-
-# create the destination directory
-$(call makepath,$(DESTPATH))
-
-# macro for copying.
-define copydirectory
-
-# everything gets copied every time.
-ALL::
-	$(call startrule,copydir) \
-	$(GNUCP) -R $(SOURCEPATH)/* $(DESTPATH) && \
-	$(GNUCHMOD) -R a+rw $(DESTPATH) \
-	$(call endrule,copydir)
-
-# CLEAN removes the whole destination directory.
-CLEAN::
-	$(call startrule,clean) \
-	$(GNURM) -rf $(DESTPATH)  \
-	$(call endrule,clean)
-
-endef # copydirectory
-
-$(eval $(copydirectory))
-
-# for WHAT reporting we have to list every file because CBR
-# wont just take a directory name and include the contents.
-
-# normally we would just use the "whatmacro" macro, which
-# handles everything nicely for us, but we are likely to be
-# generating long lists of files here and might over-run the
-# space available for a single variable :-(
-
-FINDFILES:=$(GNUFIND) $(SOURCEPATH) -type f -print | $(GNUSED) 's!$(SOURCEPATH)!$(DESTPATH)!'
-
-define whatcopies
-
-WHAT::
-	@(echo "<whatlog bldinf='$(COMPONENT_META)' mmp='$(PROJECT_META)' config='$(SBS_CONFIGURATION)'>"; \
-	$(FINDFILES) | (read LINE; \
-	while [ $$$$? -eq 0 ]; do \
-		echo "<build>$$$$LINE</build>"; \
-		read LINE; \
-	done); \
-	echo "</whatlog>") $(if $(DESCRAMBLE),2>&1 | $(DESCRAMBLE))
-
-endef # whatcopies
-
-$(eval $(whatcopies))
-
+# 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:
+#
+
+# FLM to recursively copy one directory into another.
+
+# parameters
+#
+# SOURCE_DIR	the source directory, relative to EXTENSION_ROOT
+# DEST_DIR		the destination directory, relative to EPOCROOT
+
+SOURCEPATH:=$(EXTENSION_ROOT)/$(SOURCE_DIR)
+DESTPATH:=$(EPOCROOT)/$(DEST_DIR)
+
+# create the destination directory
+$(call makepath,$(DESTPATH))
+
+# macro for copying.
+define copydirectory
+
+# everything gets copied every time.
+ALL::
+	$(call startrule,copydir) \
+	$(GNUCP) -R $(SOURCEPATH)/* $(DESTPATH) && \
+	$(GNUCHMOD) -R a+rw $(DESTPATH) \
+	$(call endrule,copydir)
+
+# CLEAN removes the whole destination directory.
+CLEAN::
+	$(call startrule,clean) \
+	$(GNURM) -rf $(DESTPATH)  \
+	$(call endrule,clean)
+
+endef # copydirectory
+
+$(eval $(copydirectory))
+
+# for WHAT reporting we have to list every file because CBR
+# wont just take a directory name and include the contents.
+
+# normally we would just use the "whatmacro" macro, which
+# handles everything nicely for us, but we are likely to be
+# generating long lists of files here and might over-run the
+# space available for a single variable :-(
+
+FINDFILES:=$(GNUFIND) $(SOURCEPATH) -type f -print | $(GNUSED) 's!$(SOURCEPATH)!$(DESTPATH)!'
+
+define whatcopies
+
+WHAT::
+	@(echo "<whatlog bldinf='$(COMPONENT_META)' mmp='$(PROJECT_META)' config='$(SBS_CONFIGURATION)'>"; \
+	$(FINDFILES) | (read LINE; \
+	while [ $$$$? -eq 0 ]; do \
+		echo "<build>$$$$LINE</build>"; \
+		read LINE; \
+	done); \
+	echo "</whatlog>") $(if $(DESCRAMBLE),2>&1 | $(DESCRAMBLE))
+
+endef # whatcopies
+
+$(eval $(whatcopies))
+
--- a/sbsv2/raptor/lib/flm/utils/prebuilt.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/utils/prebuilt.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,103 +1,103 @@
-# 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:
-#
-
-# FLM to copy pre-built binaries into the right release locations
-
-# parameters
-#
-# PRE_PLATFORM    the target of the binaries, e.g. armv5
-# PRE_TYPE        the build variant of the binaries, e.g. urel
-# BINARIES        the list of binary files, relative to EXTENSION_ROOT
-
-# The filenames in the list BINARIES may optionally have an appended "->name"
-# when the destination basename should be different from the source. For
-# example, ../bin/deb_codec66.lib->codec66.lib will create files
-# called "codec66.lib" and not "deb_codec66.lib"
-               
-# ensure that there are no nasty leading or trailing spaces
-PRE_PLATFORM:=$(strip $(PRE_PLATFORM))
-PRE_TYPE:=$(strip $(PRE_TYPE))
-
-# don't do anything unless the prebuilt binaries match what we are building
-#
-ifeq ($(PRE_PLATFORM),$(VARIANTPLATFORM))
-ifeq ($(PRE_TYPE),$(VARIANTTYPE))
-
-# the feature Invariant directory for binaries of this ilk
-INV:=$(RELEASEPATH)/$(VARIANTPLATFORM)/$(VARIANTTYPE)
-
-CREATABLEPATHS:=
-RELEASABLES:=
-
-# for any configuration (feature variant or not) add rules to copy the
-# prebuilt binaries from the source directory to the Invariant directory.
-#
-# For example,
-# cp /src/armv5/urel/my.lib /epoc32/release/armv5/urel/my.lib
-#
-# Without this you would always have to build the invariant configuration
-# before (or alongside) any feature variant configuration.
-
-define copyprebuilt
-#
-# $1 is the source file
-# $2 is the destination file
-
-ALL:: $(2)
-
-$(2): $(1)
-	$(call startrule,copyprebuilt) \
-	$(GNUCP) $(1) $(2) && \
-	$(GNUCHMOD) a+rw $(2) \
-	$(call endrule,copyprebuilt)
-
-CREATABLEPATHS:=$(INV)
-RELEASABLES:=$$(RELEASABLES) $(2)
-
-endef # copyprebuilt
-
-define copyprebuiltfile
-#
-# $1 is "name" or "name->name"
-
-ifeq ($(findstring ->,$(1)),)
-$(call copyprebuilt,$(EXTENSION_ROOT)/$(1),$(INV)/$(notdir $(1)))
-else
-$(call copyprebuilt,$(EXTENSION_ROOT)/$(word 1,$(subst ->, ,$(1))),$(INV)/$(word 2,$(subst ->, ,$(1))))
-endif
-endef # copyprebuiltfile
-
-$(eval $(foreach B,$(BINARIES),$(call copyprebuiltfile,$(B))))
-
-
-# housekeeping
-
-# make the output directories while reading the makefile,
-# as some build engines prefer this.
-$(call makepath,$(CREATABLEPATHS))
-
-# clean
-$(eval $(call GenerateStandardCleanTarget,$(RELEASABLES),$(CREATABLEPATHS)))
-
-# what
-$(eval $(call whatmacro,$(RELEASABLES)))
-
-
-endif # PRE_TYPE == VARIANTTYPE
-endif # PRE_PLATFORM == VARIANTPLATFORM
-
-
-# the end
-
+# 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:
+#
+
+# FLM to copy pre-built binaries into the right release locations
+
+# parameters
+#
+# PRE_PLATFORM    the target of the binaries, e.g. armv5
+# PRE_TYPE        the build variant of the binaries, e.g. urel
+# BINARIES        the list of binary files, relative to EXTENSION_ROOT
+
+# The filenames in the list BINARIES may optionally have an appended "->name"
+# when the destination basename should be different from the source. For
+# example, ../bin/deb_codec66.lib->codec66.lib will create files
+# called "codec66.lib" and not "deb_codec66.lib"
+               
+# ensure that there are no nasty leading or trailing spaces
+PRE_PLATFORM:=$(strip $(PRE_PLATFORM))
+PRE_TYPE:=$(strip $(PRE_TYPE))
+
+# don't do anything unless the prebuilt binaries match what we are building
+#
+ifeq ($(PRE_PLATFORM),$(VARIANTPLATFORM))
+ifeq ($(PRE_TYPE),$(VARIANTTYPE))
+
+# the feature Invariant directory for binaries of this ilk
+INV:=$(RELEASEPATH)/$(VARIANTPLATFORM)/$(VARIANTTYPE)
+
+CREATABLEPATHS:=
+RELEASABLES:=
+
+# for any configuration (feature variant or not) add rules to copy the
+# prebuilt binaries from the source directory to the Invariant directory.
+#
+# For example,
+# cp /src/armv5/urel/my.lib /epoc32/release/armv5/urel/my.lib
+#
+# Without this you would always have to build the invariant configuration
+# before (or alongside) any feature variant configuration.
+
+define copyprebuilt
+#
+# $1 is the source file
+# $2 is the destination file
+
+ALL:: $(2)
+
+$(2): $(1)
+	$(call startrule,copyprebuilt) \
+	$(GNUCP) $(1) $(2) && \
+	$(GNUCHMOD) a+rw $(2) \
+	$(call endrule,copyprebuilt)
+
+CREATABLEPATHS:=$(INV)
+RELEASABLES:=$$(RELEASABLES) $(2)
+
+endef # copyprebuilt
+
+define copyprebuiltfile
+#
+# $1 is "name" or "name->name"
+
+ifeq ($(findstring ->,$(1)),)
+$(call copyprebuilt,$(EXTENSION_ROOT)/$(1),$(INV)/$(notdir $(1)))
+else
+$(call copyprebuilt,$(EXTENSION_ROOT)/$(word 1,$(subst ->, ,$(1))),$(INV)/$(word 2,$(subst ->, ,$(1))))
+endif
+endef # copyprebuiltfile
+
+$(eval $(foreach B,$(BINARIES),$(call copyprebuiltfile,$(B))))
+
+
+# housekeeping
+
+# make the output directories while reading the makefile,
+# as some build engines prefer this.
+$(call makepath,$(CREATABLEPATHS))
+
+# clean
+$(eval $(call GenerateStandardCleanTarget,$(RELEASABLES),$(CREATABLEPATHS)))
+
+# what
+$(eval $(call whatmacro,$(RELEASABLES)))
+
+
+endif # PRE_TYPE == VARIANTTYPE
+endif # PRE_PLATFORM == VARIANTPLATFORM
+
+
+# the end
+
--- a/sbsv2/raptor/lib/flm/utils/utility.xml	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/utils/utility.xml	Wed Jun 23 16:56:47 2010 +0800
@@ -1,28 +1,28 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../../schema/build/2_0.xsd">
-	<!-- utility interfaces : handy FLMs for simple things -->
-
-	<interface name="utility.base" extends="base.flm" abstract="true">
-		<param name='EPOCROOT'/>
-		<param name='EPOCBLD'/>
-		<param name='EXTENSION_ROOT'/>
-	</interface>
-
-	<interface name="utility.copydir" extends="utility.base" flm="copydir.flm">
-		<param name="SOURCE_DIR"/>
-		<param name="DEST_DIR"/>
-	</interface>
-
-	<interface name="utility.prebuilt" extends="utility.base" flm="prebuilt.flm">
-		<!-- from the configuration -->
-		<param name="GNUCHMOD"/>
-		<param name="GNUCP"/>
-		<param name="RELEASEPATH"/>
-		<param name="VARIANTPLATFORM"/>
-		<param name="VARIANTTYPE"/>
-		<!-- from the bld.inf -->
-		<param name="BINARIES"/>
-		<param name="PRE_PLATFORM"/> 
-		<param name="PRE_TYPE"/>
-	</interface>
-</build>
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<build xmlns="http://symbian.com/xml/build" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symbian.com/xml/build ../../../schema/build/2_0.xsd">
+	<!-- utility interfaces : handy FLMs for simple things -->
+
+	<interface name="utility.base" extends="base.flm" abstract="true">
+		<param name='EPOCROOT'/>
+		<param name='EPOCBLD'/>
+		<param name='EXTENSION_ROOT'/>
+	</interface>
+
+	<interface name="utility.copydir" extends="utility.base" flm="copydir.flm">
+		<param name="SOURCE_DIR"/>
+		<param name="DEST_DIR"/>
+	</interface>
+
+	<interface name="utility.prebuilt" extends="utility.base" flm="prebuilt.flm">
+		<!-- from the configuration -->
+		<param name="GNUCHMOD"/>
+		<param name="GNUCP"/>
+		<param name="RELEASEPATH"/>
+		<param name="VARIANTPLATFORM"/>
+		<param name="VARIANTTYPE"/>
+		<!-- from the bld.inf -->
+		<param name="BINARIES"/>
+		<param name="PRE_PLATFORM"/> 
+		<param name="PRE_TYPE"/>
+	</interface>
+</build>
--- a/sbsv2/raptor/lib/flm/win32.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,688 +1,700 @@
-# 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:
-# WINSCW EXE/DLL/IMPLIB/LIB Function Like Makefile (FLM)
-# Knows how to build all possible executables for the WINSCW emulator build
-#
-#
-
-# passed in values, stripped of whitespace
-COPY_FOR_STATIC_LINKAGE:=$(strip $(COPY_FOR_STATIC_LINKAGE))
-DEFFILE:=$(strip $(DEFFILE))
-DEFFILEKEYWORD:=$(strip $(DEFFILEKEYWORD))
-EPOCALLOWDLLDATA:=$(strip $(EPOCALLOWDLLDATA))
-EXPORTLIBRARY:=$(strip $(EXPORTLIBRARY))
-BASEADDRESS:=$(strip $(BASEADDRESS))
-LINKAS:=$(strip $(LINKAS))
-NOEXPORTLIBRARY:=$(strip $(NOEXPORTLIBRARY))
-SECUREID:=$(strip $(SECUREID))
-UID2:=$(strip $(UID2))
-UID3:=$(strip $(UID3))
-VENDORID:=$(strip $(VENDORID))
-VID:=$(strip $(VID))
-WIN32_HEADERS:=$(strip $(WIN32_HEADERS))
-
-# local variables
-BINDIR:=
-BINDIRSTATICLINK:=
-BINTARGET:=
-BINTARGETSTATICLINK:=
-BLDDIR:=
-CHECKLIB_TYPE:=
-CREATABLEPATHS:=
-CLEANTARGETS:=
-CW_RUNTIME:=
-ENTRYSYMBOL:=
-IMPORTLIBLINKAS:=
-IMPORTLIBTARGET:=
-LIBDIR:=
-LINKER_FIRSTSTATLIB:=
-MAINLINKAS:=
-NEWLIBFILE:=
-RELEASABLES:=
-STATLIBDIR:=
-STDCPP_BUILD:=
-STDCPPTAGFILE:=
-UID1:=
-WIN32_LIBRARIES:=
-
-# FIVESPACES variable created to ensure that a suitable gap of space characters can
-# be placed between the separate arguments in the call to a tool (if required).
-# This is a workaround for a problem in Cygwin, where separate arguments are interpreted
-# as a single argument when passed to bash.
-FIVESPACES=$(BLANK)     $(BLANK)
-
-# CW runtime varies based on TARGETTYPE requirements, with wrapper FLMs dictating the choice
-# We override a CW-specific environment variable to do this, in common with ABLD
-ifeq ($(CW_STATIC_RUNTIME),1)
-  CW_RUNTIME:=$(CW_RUNTIME_STATIC)
-  CFLAGS:=$(CFLAGS) $(OPT.RUNTIME)staticmulti
-else
-  CW_RUNTIME:=$(CW_RUNTIME_NONSTATIC)
-  CFLAGS:=$(CFLAGS) $(OPT.RUNTIME)dllmulti
-endif
-MWSym2LibraryFiles:=$(subst $(CHAR_SPACE),$(DIRSEP),$(CW_RUNTIME) $(CW_DEFAULT_LIBS))
-ifneq ($(WIN32_LIBRARY),)
-  WIN32_HEADERS:=1
-  WIN32_LIBRARIES:=$(addprefix $(OPT.LIBFILE),$(WIN32_LIBRARY))
-endif
-
-# top-level definitions
-BINDIR:=$(RELEASEPATH)/$(FULLVARIANTPATH)
-
-# TARGETPATH and COPY_FOR_STATIC_LINKAGE only apply when TARGETPATH is a sub-directory of /sys/bin
-TARGETPATH_APPEND:=$(subst \,/,$(TARGETPATH))
-ifneq ($(findstring /sys/bin/,$(TARGETPATH_APPEND)),)
-  ifeq ($(COPY_FOR_STATIC_LINKAGE),1)
-    BINDIRSTATICLINK:=$(BINDIR)
-  endif
-  BINDIR:=$(BINDIR)/z$(TARGETPATH_APPEND)
-else
-  COPY_FOR_STATIC_LINKAGE:=0
-endif
-
-BLDDIR:=$(OUTPUTPATH)/$(FULLVARIANTPATH)
-LIBDIR:=$(RELEASEPATH)/$(LINKPATH)
-STATLIBDIR:=$(RELEASEPATH)/$(FULLVARIANTPATH)
-CREATABLEPATHS:=$(BLDDIR) $(BINDIR) $(BINDIRSTATICLINK)
-
-# Deduce whether we should be performing a build with standard CPP characteristics
-# This operates differently per-OS release, although OE TARGETTYPEs always build with standard CPP traits
-ifeq ($(OPEN_ENVIRONMENT),1)
-  STDCPP_BUILD:=1
-endif
-
-ifeq ($(SUPPORTS_STDCPP_NEWLIB),1)
-  ifeq ($(NOSTDCPP),1)
-    STDCPP_BUILD:=
-  else
-    ifeq ($(STDCPP),1)
-      STDCPP_BUILD:=1
-    endif
-  endif
-
-  ifneq ($(NEWLIB),)
-    NEWLIBFILE:=$(STATLIBDIR)/$(NEWLIB)
-  else
-    ifeq ($(SYSTEM_TARGET),1)
-      NEWLIBFILE:=$(STATLIBDIR)/$(DEFAULT_SYSTEM_NEWLIB)
-    else
-      NEWLIBFILE:=$(STATLIBDIR)/$(DEFAULT_NORMAL_NEWLIB)
-    endif
-  endif
-endif
-
-ifeq ($(STDCPP_BUILD),1)
-  CDEFS:=$(CDEFS) $(STDCPP_DEF)
-  SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(STDCPP_INCLUDE)
-  CFLAGS:=$(CFLAGS) $(OPT.WCHAR) on
-  CHECKLIB_TYPE:=$(OPT.CHECKLIB.STDCPP)
-  STDCPPTAGFILE:=$(OPT.LIBPATH)$(EPOCROOT)/epoc32/tools/tag $(OPT.SEARCH) tag_coff
-else
-  CFLAGS:=$(CFLAGS) $(OPT.WCHAR) off
-  CHECKLIB_TYPE:=$(OPT.CHECKLIB.SYMCPP)
-endif
-
-ifeq ($(WIN32_HEADERS),1)
-  CDEFS:=$(CDEFS) WIN32
-  CDEFS:=$(CDEFS) _WINDOWS
-  CFLAGS:=$(CFLAGS) $(OPT.STDINC)
-else
-  CFLAGS:=$(CFLAGS) $(OPT.NOSTDINC)
-endif
-
-# get the compiler to generate dependencies for us?
-ifeq ($(DEPEND_SKIP),)
-  CFLAGS:=$(CFLAGS) $(OPT.DEPEND)
-endif
-
-# specifics relating to the base type of the target being processed
-ifeq ($(BASE_TYPE),dll)
-  # Special case, although this should be dealt with in the wrapper FLM in a better way
-  ifeq ($(TARGETTYPE),exexp)
-    CDEFS:=$(CDEFS) __EXE__
-    ENTRYSYMBOL:=__E32Startup
-    LFLAGS:=$(LFLAGS) $(OPT.NOENTRY)
-    UID1:=1000007a
-  else
-    CDEFS:=$(CDEFS) __DLL__
-    ENTRYSYMBOL:=__E32Dll
-    LFLAGS:=$(LFLAGS) $(OPT.MAINENTRYPOINT)__Win32DllMain@12
-    UID1:=10000079
-  endif
-  LFLAGS:=$(LFLAGS) $(OPT.SHARED)
-
-  ifneq ($(BASEADDRESS),)
-    LFLAGS:=$(LFLAGS) $(OPT.IMAGEBASE)$(BASEADDRESS)
-  endif
-
-  ifeq ($(FIRST_STATLIB),)
-    BASE_TYPE_STATLIB:=edll.lib
-  else
-    BASE_TYPE_STATLIB:=$(FIRST_STATLIB)
-  endif
-endif
-ifeq ($(BASE_TYPE),exe)
-  CDEFS:=$(CDEFS) __EXE__
-  ENTRYSYMBOL:=?_E32Bootstrap@@YGXXZ
-  UID1:=1000007a
-
-  ifeq ($(FIRST_STATLIB),)
-    BASE_TYPE_STATLIB:=eexe.lib
-  else
-    BASE_TYPE_STATLIB:=$(FIRST_STATLIB)
-  endif
-endif
-
-ifeq ($(FIRSTLIB),)
-  LINKER_FIRSTSTATLIB:=$(BASE_TYPE_STATLIB)
-else
-  LINKER_FIRSTSTATLIB:=$(FIRSTLIB)
-endif
-
-
-BINTARGET:=$(BINDIR)/$(TARGET).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(TARGETTYPE))
-
-
-# Run trace compiler #####################################
-TRACE_MARKER_PATH:=$(OUTPUTPATH)
-
-ifeq ($(UID3),)
-  ifeq ($(UID2),)
-    USE_TRACE_COMPILER:=
-  else
-    UID_TC:=$(UID2)
-  endif
-else
-  UID_TC:=$(UID3)
-endif
-
-# USE_TRACE_COMPILER defaults to blank in Raptor config.
-# Users can turn TC on by setting it to 1 in user config.
-ifneq ($(USE_TRACE_COMPILER),) 
-  include $(FLMHOME)/tracecompiler.mk
-endif
-
-
-####################
-## IMPORT LIBRARY ##
-####################
-
-IMPORTLIBLINKAS:=$(TARGET).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(TARGETTYPE))
-# LINKAS, if supplied, only applies to IMPLIB TARGETTYPEs
-ifeq ($(BASE_TYPE),importlib)
-  ifneq ($(LINKAS),)
-    IMPORTLIBLINKAS:=$(LINKAS)
-  else
-    IMPORTLIBLINKAS:=$(TARGET).dll
-  endif
-endif
-
-ifneq ($(EXPORTLIBRARY),)
-  IMPORTLIBTARGET:=$(LIBDIR)/$(EXPORTLIBRARY).lib
-else
-  IMPORTLIBTARGET:=$(LIBDIR)/$(TARGET).lib
-endif
-
-# Regardless of whether a TARGETTYPE normally supports an import library, always attempt
-# to generate one if an explicit DEFFILE keyword was listed
-ifeq ($(DEFFILEKEYWORD),1)
-  SUPPORTS_IMPORT_LIBRARY:=1
-endif
-
-ifeq ($(SUPPORTS_IMPORT_LIBRARY),1)
-  ifneq ($(NOEXPORTLIBRARY),1)
-    ifneq ($(TARGET_$(call sanitise,$(IMPORTLIBTARGET))),1)
-      CLEANTARGETS:=$(CLEANTARGETS) $(if $(or $(EXPORTUNFROZEN),$(DEFFILE)),$(IMPORTLIBTARGET))
-      RELEASABLES:=$(RELEASABLES) $(if $(or $(EXPORTUNFROZEN),$(DEFFILE)),$(IMPORTLIBTARGET))
-
-      # import libraries are generated to the UDEB release directory
-      ifneq ($(VARIANTTYPE),udeb)
-        CREATABLEPATHS:=$(CREATABLEPATHS) $(if $(or $(EXPORTUNFROZEN),$(DEFFILE)),$(LIBDIR))
-      endif
-
-      ifneq ($(EXPORTUNFROZEN),)
-        # EXPORTUNFROZEN amounts to doing the stage-two link with the makedef generated temporary .def file but creating a .lib
-        # file as a side-effect of linking.  The import library is therefore dependent on the final binary in this instance.
-        $(info <warning project='$(PROJECT_META)' component='$(COMPONENT_META)'>EXPORTUNFROZEN present in $(PROJECT_META) - unfrozen exports will be represented in import library.</warning> )
-        $(IMPORTLIBTARGET): $(BINTARGET)
-        $(eval TARGET_$(call sanitise,$(IMPORTLIBTARGET)):=1)
-      else
-        ifneq ($(DEFFILE),)
-          # If a .def file physically exists (either explicitly via DEFFILE or implicitly in the correct place) then we
-          # generate an import library with reference to it
-          PREPPEDDEFFILE:=$(BLDDIR)/$(TARGET).prep.def
-          CLEANTARGETS:=$(CLEANTARGETS) $(PREPPEDDEFFILE)
-
-          define win32def2lib
-            $(IMPORTLIBTARGET): $(DEFFILE)
-	          $(call startrule,win32def2lib) \
-	          $(PREPDEF) "$(DEFFILE)" "$(PREPPEDDEFFILE)" && \
-	          $(LD) $(PREPPEDDEFFILE) $(OPT.IMPORTLIB) -o "$$@" $(OPT.ADDCOMMAND) "out:$(IMPORTLIBLINKAS)" $(OPT.WARNINGS) off \
-	          $(call endrule,win32def2lib)
-          endef
-          $(eval $(win32def2lib))
-          $(eval TARGET_$(call sanitise,$(IMPORTLIBTARGET)):=1)
-        endif
-      endif
-    endif
-  endif
-endif
-
-
-ifneq ($(BASE_TYPE),importlib)
-
-  #############
-  ## COMPILE ##
-  #############
-
-  ifeq ($(COPY_FOR_STATIC_LINKAGE),1)
-    BINTARGETSTATICLINK:=$(BINDIRSTATICLINK)/$(TARGET).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(TARGETTYPE))
-  endif
-
-  CLEANTARGETS:=$(CLEANTARGETS) $(BINTARGET) $(BINTARGETSTATICLINK)
-  RELEASABLES:=$(RELEASABLES) $(BINTARGET) $(BINTARGETSTATICLINK)
-
-  # work on a local source files list
-  SRCFILES:=$(SOURCE)
-  # and there may be more source for stage 2 in OE builds
-  SRCFILES_OE:=
-
-  ifneq ($(BASE_TYPE),staticlib)
-    # add the generated UID source file
-    GENSOURCE:=$(BLDDIR)/$(TARGET).UID.CPP
-    SRCFILES:=$(SRCFILES) $(GENSOURCE)
-
-    # the generated symbol lookup source file for Open Environment.
-    # this only gets linked in at stage 2
-    SYMSOURCE:=$(if $(OPEN_ENVIRONMENT),$(BLDDIR)/$(TARGET)_SYM_.cpp,)
-    SRCFILES_OE:=$(SYMSOURCE)
-
-    CLEANTARGETS:=$(CLEANTARGETS) $(GENSOURCE) $(SYMSOURCE)
-
-    ifeq ($(UID2),00000000)
-      ifneq ($(UID2_DEFAULT),)
-        UID2:=$(UID2_DEFAULT)
-      endif
-    endif
-
-    ifeq ($(SECUREID),)
-      SECUREID:=$(UID3)
-    endif
-
-    define win32generateUIDcpp
-      $(GENSOURCE): $(PROJECT_META)
-	    $(call startrule,win32generateUIDcpp,,) \
-	    echo "// SBS-generated uid source file" > $$@ && \
-	    echo "#include <e32cmn.h>" >> $$@ && \
-	    echo "#pragma data_seg(\".SYMBIAN\")" >> $$@ && \
-	    echo "__EMULATOR_IMAGE_HEADER2(0x$(UID1),0x$(UID2),0x$(UID3),EPriority$(EPOCPROCESSPRIORITY),0x$(CAPABILITYFLAG1),0x$(CAPABILITYFLAG2),0x$(SECUREID),0x$(VENDORID),0x$(VERSIONHEX),$(EPOCALLOWDLLDATA))" >> $$@ && \
-	    echo "#pragma data_seg()" >> $$@ \
-	    $(call endrule,win32generateUIDcpp)
-    endef
-    $(eval $(win32generateUIDcpp))
-  endif # neq $(BASE_TYPE),staticlib
-
-  # object files
-  OBJECTFILES:=$(patsubst %,$(BLDDIR)/%,$(addsuffix .o,$(basename $(notdir $(call allsuffixsubst,.cia .CIA .Cia,_.cia,$(SRCFILES))))))
-  OBJECTFILES:=$(patsubst %.UID.o,%_UID_.o,$(OBJECTFILES))
-
-  # object file extras for stage 2
-  OBJECTFILES_OE:=$(patsubst %,$(BLDDIR)/%,$(addsuffix .o,$(basename $(notdir $(SRCFILES_OE)))))
-
-  CLEANTARGETS:=$(CLEANTARGETS) $(OBJECTFILES) $(OBJECTFILES_OE)
-
-  # include paths and preinclude file
-  UINCLUDE:=$(patsubst %,$(OPT.USERINCLUDE)%,$(USERINCLUDE))
-  SINCLUDE:=$(patsubst %,$(OPT.SYSINCLUDE)%,$(SYSTEMINCLUDE))
-  PINCLUDE:=$(OPT.PREINCLUDE)$(notdir $(PRODUCT_INCLUDE))
-
-  #INCLUDES:=$(UINCLUDE) $(OPT.SPLITINCLUDE) $(SINCLUDE) $(PINCLUDE)
-  INCLUDES:=$(OPT.SPLITINCLUDE) $(UINCLUDE) $(SINCLUDE) $(PINCLUDE)
-
-  # macro definitions
-  DEFINES:=$(call makemacrodef,$(OPT.DEFINE),$(CDEFS) $(TARGET_MACRO))
-
-
-  # $(1) is the name of the source file, $(2) is the extension to map it to e.g. .o
-  # no space in front of function body
-  define mapwin32file
-    $(patsubst %.UID$(2),%_UID_$(2),$(BLDDIR)/$(addsuffix $2,$(basename $(notdir $(call allsuffixsubst,.cia .CIA .Cia,_.cia,$(1))))))
-  endef
-
-  # compile all source files, creating and including compiler generated dependency files along the way
-  # SED is used to (a) remove relatively pathed "object_file: source_file" references that can appear
-  # with some versions of mwccsym2 and (b) convert slashes
-  define win32compile2object
-
-    $(eval DEPENDFILENAME:=$(call mapwin32file,$(1),.o.d))
-    $(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
-
-    $(call mapwin32file,$(1),.o): $(1) $(PROJECT_META) $(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT) $(if $(USE_TRACE_COMPILER),$(TRACE_MARKER))
-	  $(call startrule,win32compile2object,,$(1)) \
-	  $(CC) $$(if $$(filter %.C,$(1)),-lang c) $(CFLAGS) $(OPTION_CW) \
-	  $(if $(STDCPP_BUILD),$$(if $$(filter %.c %.C,$(1)),,$$(call makemacrodef,$(OPT.DEFINE),$(STDCPP_WCHAR_DEF))),) \
-	  $(DEFINES) $(INCLUDES) $(OPT.OUT)"$$@" "$(1)" && \
-	  $(GNUSED) 's#\\\\\(.\)#/\1#g;s#/ #\\\ #g;s#\([A-Za-z]:\)\\\\#\1/#g;1,1s#.*: .* \(.\)\?$$$$#$(call mapwin32file,$(1),.o): $1 \1#' $(call mapwin32file,$(1),.dep) > $(call mapwin32file,$(1),.o.d) \
-	  $(call endrule,win32compile2object)
-
-    CLEANTARGETS:=$$(CLEANTARGETS) $(call mapwin32file,$(1),.dep)
-
-    CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
-    ifneq "$(DEPENDFILE)" ""
-    ifeq ($(NO_DEPEND_INCLUDE),)
-      ifeq "$(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS)))" ""
-        -include $(DEPENDFILE)
-      endif
-    endif
-    endif
-
-    # individual source file compilation
-    SOURCETARGET_$(call sanitise,$(1)): $(call mapwin32file,$(1),.o)
-
-  endef
-
-  # List target, depends on object file
-  define win32list
-  LISTING:: $(OBJECTFILES) $(OBJECTFILES_OE)
-	$(call startrule,win32listing) \
-	$(CC) $(OPT.LISTING) $(patsubst %.UID.o,%_UID_.o,$(BLDDIR)/$(addsuffix .o,$(basename $(notdir $(1))))) -o $(basename $1).WINSCW.lst \
-	$(call endrule,win32listing)
-  endef
-
-  $(foreach SRCFILE,$(SRCFILES) $(SRCFILES_OE),$(eval $(call win32compile2object,$(SRCFILE))))
-  $(foreach SRCFILE,$(SRCFILES) $(SRCFILES_OE),$(eval $(call win32list,$(SRCFILE))))
-
-  ######################
-  ## RESOURCE COMPILE ##
-  ######################
-
-  # If Python has been used to construct the environment on Windows then the standard MW include path environment
-  # variable will have been munged to UPPERCASE.
-  STDMWCINCLUDEPATHS:=$(if $(MWCSym2Includes),$(MWCSym2Includes),$(MWCSYM2INCLUDES))
-
-  define win32resourcecompile
-    # Note that two calls are made to the resource compiler here.  There seems to be no means to override the
-    # default behaviour of dumping dependency files into the CWD when using -MD.  So - we compile once for real,
-    # and then pipe dependency output through SED afterwards to create the dependency file where we want it
-
-    $(eval DEPENDFILENAME:=$(call mapwin32file,$(1),.res.d))
-    $(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
-
-    $(call mapwin32file,$(1),.res): $(1) $(PROJECT_META) $(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT)
-	  $(call startrule,win32resourcecompile,,$(1)) \
-	  MWCIncludes='$(STDMWCINCLUDEPATHS)' $(RC) $(OPT.OUT)"$$@" "$(1)" && \
-	  MWCIncludes='$(STDMWCINCLUDEPATHS)' $(RC) -make $(OPT.OUT)"$$@" "$(1)" | \
-	  $(GNUSED) 's#\\\\\(.\)#/\1#g;s#/ #\\\ #g;s#\([A-Za-z]:\)\\\\#\1/#g;1,1s#.*: .* \(.\)\?$$$$#$(call mapwin32file,$(1),.res): $1 \1#' > $(call mapwin32file,$(1),.res.d) \
-	  $(call endrule,win32resourcecompile)
-
-    CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
-    ifneq "$(DEPENDFILE)" ""
-    ifeq ($(NO_DEPEND_INCLUDE),)
-      ifeq "$(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS)))" ""
-        -include $(DEPENDFILE)
-      endif
-    endif
-    endif
-
-  endef
-
-  $(foreach WIN32RESOURCEFILE,$(WIN32_RESOURCE),$(eval $(call win32resourcecompile,$(WIN32RESOURCEFILE))))
-  OBJECTFILES:=$(OBJECTFILES) $(patsubst %,$(BLDDIR)/%,$(addsuffix .res,$(basename $(notdir $(WIN32_RESOURCE)))))
-
-  ##################
-  ## LINK/ARCHIVE ##
-  ##################
-
-  # libraries
-  STATICLIBS:=$(patsubst %,%.lib,$(STATICLIBRARY))
-  STATICLIBFILES:=$(patsubst %,$(STATLIBDIR)/%,$(STATICLIBS))
-  LINKER_FIRSTSTATLIBFILE:=$(STATLIBDIR)/$(LINKER_FIRSTSTATLIB)
-
-  ifeq ($(VARIANTTYPE),urel)
-    LINKLIBS:=$(patsubst %.dso,%.lib,$(LIBRARY))
-  else
-    LINKLIBS:=$(patsubst %.dso,%.lib,$(LIBRARY_DEBUG))
-  endif
-
-  LINKLIBFILES:=$(patsubst %,$(LIBDIR)/%,$(LINKLIBS))
-
-  MAP:=
-  ifneq ($(BASE_TYPE),staticlib)
-    ifneq ($(BASE_TYPE),importlib)
-      # link map file (urel only)
-      ifeq ($(VARIANTTYPE),urel)
-        MAP:=$(OPT.MAP)$(BINTARGET).map
-        CLEANTARGETS:=$(CLEANTARGETS) $(BINTARGET).map
-        RELEASABLES:=$(RELEASABLES) $(BINTARGET).map
-      endif
-    endif
-  endif
-
-  # all object files are listed in a response file to minimise the length of linker calls
-  OBJECTFILES_LRF:=$(BLDDIR)/$(TARGET)_$(VARIANTTYPE)_objects.lrf
-  CLEANTARGET:=$(CLEANTARGETS) $(OBJECTFILES_LRF)
-
-  define groupin10
-	$(if $1,@echo -e $(foreach L,$(wordlist 1,10,$1),"$(L)\\n") >> $(OBJECTFILES_LRF),)
-	$(if $1,$(call groupin10,$(wordlist 11,$(words $1),$1)),@true)
-  endef
-
-  #
-  # Archive
-  #
-  ifeq ($(BASE_TYPE),staticlib)
-    define win32archive
-      $(BINTARGET): $(OBJECTFILES)
-	    @echo "" > $(OBJECTFILES_LRF);
-		$(call groupin10,$(notdir $(OBJECTFILES))) ;
-	    $(call startrule,win32archive) \
-	    $(LD) $(OPT.STATICLIBRARY) $(LFLAGS) $(OPT.NOIMPLIB) $(WIN32_LIBRARIES) $(OPT.OUT)"$$@" $(STDCPPTAGFILE) $(OPT.LIBPATH)$(BLDDIR) $(OPT.SEARCH) @$(OBJECTFILES_LRF) \
-	    $(if $(SAVESPACE),; $(GNURM) -rf $(BLDDIR); true,) \
-	    $(call endrule,win32archive)
-    endef
-    $(eval $(win32archive))
-  endif
-
-  ifneq ($(EPOCHEAPSIZEMIN_DEC_KB),)
-    LFLAGS:=$(LFLAGS) $(OPT.HEAPRESERVE)$(EPOCHEAPSIZEMAX_DEC_KB) $(OPT.HEAPCOMMIT)$(EPOCHEAPSIZEMIN_DEC_KB)
-  endif
-
-  #
-  # Simple link
-  #
-  ifeq ($(BASE_TYPE),exe)
-    define win32simplelink
-      $(BINTARGET).map: $(BINTARGET)
-
-      $(BINTARGET): $(OBJECTFILES) $(LINKER_FIRSTSTATLIBFILE) $(NEWLIBFILE) $(STATICLIBFILES) $(LINKLIBFILES)
-	    @echo "" > $(OBJECTFILES_LRF);
-		$(call groupin10,$(notdir $(OBJECTFILES))) ;
-	    $(call startrule,win32simplelink) \
-	    $(if $(SUPPORTS_STDCPP_NEWLIB),$(if $(STATICLIBFILES),$(CHECKLIB) $(CHECKLIB_TYPE) $(OPT.CHECKLIB.WIN32) $(STATICLIBFILES) &&,),) \
-	    MWSym2LibraryFiles="$(MWSym2LibraryFiles)" $(LD) $(LFLAGS) $(OPT.MENTRYPOINT)$(ENTRYSYMBOL) $(MAP) $(LINKER_FIRSTSTATLIBFILE) $(NEWLIBFILE) $(WIN32_LIBRARIES) $(STATICLIBFILES) $(LINKLIBFILES) $(OPT.OUT)"$$@" $(OPT.NOIMPLIB) $(OPT.LIBPATH)$(BLDDIR) $(OPT.SEARCH) @$(OBJECTFILES_LRF) \
-	    $(if $(SAVESPACE),; $(GNURM) -rf $(BLDDIR); true,) \
-	    $(call endrule,win32simplelink)
-    endef
-    $(eval $(win32simplelink))
-  endif
-
-  #
-  # Two stage link
-  #
-  ifeq ($(BASE_TYPE),dll)
-    TMP_IMPLIB:=$(BLDDIR)/$(TARGET).lib
-    TMP_INFFILE:=$(BLDDIR)/$(TARGET).inf
-    TMP_SYMFILE:=$(if $(OPEN_ENVIRONMENT),$(BLDDIR)/$(TARGET).sym,)
-    TMP_TARGET:=$(BLDDIR)/$(TARGET).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(TARGETTYPE))
-    TMP_DEFFILE:=$(BLDDIR)/$(TARGET).def
-
-    CLEANTARGETS:=$(CLEANTARGETS) $(TMP_IMPLIB) $(TMP_INFFILE) $(TMP_TARGET) $(TMP_DEFFILE) $(TMP_SYMFILE)
-
-    MAKEDEF_ARGS:=-absent $(ENTRYSYMBOL) -Inffile  $(call dblquote,$(TMP_INFFILE)) $(NAME_LOOKUP)
-
-    ifeq ($(SYSTEM_TARGET),1)
-        MAKEDEF_ARGS:=$(MAKEDEF_ARGS) -SystemTargetType
-    endif
-
-    ifneq ($(FIXED_EXPORT),)
-      # Fixed export TARGETTYPE, but with possibility of a .def file if explicitly specified and available
-      ifeq ($(DEFFILEKEYWORD),1)
-        ifneq ($(DEFFILE),)
-          MAKEDEF_ARGS:=$(MAKEDEF_ARGS) -Frzfile $(call dblquote,$(DEFFILE))
-        endif
-      endif
-      MAKEDEF_ARGS:=$(MAKEDEF_ARGS) -1 $(FIXED_EXPORT)
-    else
-      # Variable export TARGETTYPE with either deduced or explicitly specified .def file (if available)
-      ifneq ($(DEFFILE),)
-        MAKEDEF_ARGS:=$(MAKEDEF_ARGS) -Frzfile $(call dblquote,$(DEFFILE))
-      endif
-    endif
-
-
-    ifneq ($(EXPORTSUNFROZEN),)
-    	LIBRARY: $(TMP_IMPLIB)
-    endif
-
-    define win32stageonelink
-      # Stage One
-      # Link by name, generating temporary main binary and import library.
-      $(TMP_IMPLIB): $(TMP_TARGET)
-
-      $(TMP_TARGET): $(OBJECTFILES) $(LINKER_FIRSTSTATLIBFILE) $(NEWLIBFILE) $(STATICLIBFILES) $(LINKLIBFILES)
-	    @echo "" > $(OBJECTFILES_LRF);
-		$(call groupin10,$(notdir $(OBJECTFILES))) ;
-	    $(call startrule,win32stageonelink) \
-	    $(if $(SUPPORTS_STDCPP_NEWLIB),$(if $(STATICLIBFILES),$(CHECKLIB) $(CHECKLIB_TYPE) $(OPT.CHECKLIB.WIN32) $(STATICLIBFILES) &&,),) \
-	    MWSym2LibraryFiles="$(MWSym2LibraryFiles)" $(LD) $(LFLAGS) $(OPT.MENTRYPOINT)$(ENTRYSYMBOL) $(OPT.EXPORT)$(EXPORT_TYPE) $(OPT.NOCOMPACTIMPORTLIB) $(OPT.ADDCOMMAND) "out:$(TARGET).$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(TARGETTYPE))" $(OPT.WARNINGS) off $(OPT.IMPLIB)"$(TMP_IMPLIB)" $(OPT.OUT)"$(TMP_TARGET)" $(LINKER_FIRSTSTATLIBFILE) $(NEWLIBFILE) $(WIN32_LIBRARIES) $(STATICLIBFILES) $(LINKLIBFILES) $(OPT.LIBPATH)$(BLDDIR) $(OPT.SEARCH) @$(OBJECTFILES_LRF) \
-	    $(call endrule,win32stageonelink)
-    endef
-    $(eval $(win32stageonelink))
-
-    define win32processexports
-      # Process exports
-      # Generate a descriptive info file from the import library.
-      # Push info file through MAKEDEF to generated a valid .def file for link by ordinal.
-      $(TMP_DEFFILE): $(TMP_IMPLIB)
-	    $(call startrule,win32processexports) \
-	    $(LD) $(LFLAGS_INFGEN) $(OPT.OUT)"$(TMP_INFFILE)" "$(TMP_IMPLIB)" && \
-	    $(MAKEDEF) $(MAKEDEF_ARGS) "$$@" \
-	    $(call endrule,win32processexports)
-    endef
-    $(eval $(win32processexports))
-
-    ifeq ($(OPEN_ENVIRONMENT),1)
-      define win32processoeexports
-   	    # Process additional exports for Open Environment
-        # Generate a symbol file from the temporary DLL.
-        # Generate a C++ source file from the symbol file
-
-        $(TMP_SYMFILE): $(TMP_TARGET)
-	      $(call startrule,win32generatesymfile) \
-	      $(LD) $(LFLAGS_SYMGEN) $(OPT.OUT)"$(TMP_SYMFILE)" "$(TMP_TARGET)" \
-	      $(call endrule,win32generatesymfile)
-
-        $(SYMSOURCE): $(TMP_SYMFILE)
-	      $(call startrule,win32generatesymcpp) \
-	      $(SYMLOOKUPUTIL) $(OPT.OUT)"$(SYMSOURCE)" $(OPT.SYM)"$(TMP_SYMFILE)" $(SYMLOOKUPARGS) \
-	      $(call endrule,win32generatesymcpp)
-      endef
-      $(eval $(win32processoeexports))
-    endif
-
-    define win32stagetwolink
-      # Stage Two
-      # Link by ordinal, based on a previously MAKEDEF-generated temporary .def file
-      # Optionally create an import library if EXPORTUNFROZEN is specified
-      #
-      $(BINTARGET).map: $(BINTARGET)
-
-      $(BINTARGET): $(OBJECTFILES) $(OBJECTFILES_OE) $(LINKER_FIRSTSTATLIBFILE) $(STATICLIBFILES) $(NEWLIBFILE) $(LINKLIBFILES) $(TMP_DEFFILE)
-	    @echo "" > $(OBJECTFILES_LRF);
-		$(call groupin10,$(notdir $(OBJECTFILES) $(OBJECTFILES_OE))) ;
-	    $(call startrule,win32stagetwolink) \
-	    MWSym2LibraryFiles="$(MWSym2LibraryFiles)" \
-	    $(LD) $(LFLAGS) $(OPT.DEFFILE)$(TMP_DEFFILE) $(MAP) $(LINKER_FIRSTSTATLIBFILE) $(NEWLIBFILE) $(WIN32_LIBRARIES) $(STATICLIBFILES) $(LINKLIBFILES) \
-	    $(OPT.OUT)"$$@" \
-	    $(if $(EXPORTUNFROZEN),$(OPT.IMPLIB)$(IMPORTLIBTARGET),$(OPT.NOIMPLIB)) \
-	    $(OPT.LIBPATH)$(BLDDIR) $(OPT.SEARCH) @$(OBJECTFILES_LRF) \
-	    $(if $(SAVESPACE),; $(GNURM) -rf $(BLDDIR); true,) \
-	    $(call endrule,win32stagetwolink)
-    endef
-    $(eval $(win32stagetwolink))
-
-    define win32copyforstaticlink
-      # Copy additonal binary to "traditional" output location (if required)
-      $(BINTARGETSTATICLINK): $(BINTARGET)
-	    $(call startrule,win32copyforstaticlink) \
-	    $(GNUCP) $$< $$@ \
-	    $(call endrule,win32copyforstaticlink)
-    endef
-    ifeq ($(COPY_FOR_STATIC_LINKAGE),1)
-      $(eval $(win32copyforstaticlink))
-    endif
-
-    define e32freeze
-      # DLL-type targets that support import library generation support freezing of exports using EFREEZE
-      FREEZE:: $(1)
-	    $(call startrule,freeze,,$(RESOLVED_DEFFILE)) \
-	    $(EFREEZE) $(EFREEZE_REMOVE_OPTION) "$(RESOLVED_DEFFILE)" $(FIVESPACES) "$(2)" \
-	    $(call endrule,freeze)
-    endef
-    # Create only one freeze target per urel/udeb variant as the interface won't differ between them
-    # Only create a freeze target if the component supports import library generation
-    ifneq ($(TARGET_$(call sanitise,$(IMPORTLIBTARGET))_FREEZE),1)
-      ifeq ($(SUPPORTS_IMPORT_LIBRARY),1)
-        $(eval $(call e32freeze,$(BINTARGET),$(TMP_DEFFILE)))
-        $(eval TARGET_$(call sanitise,$(IMPORTLIBTARGET))_FREEZE:=1)
-      endif
-    endif
-  endif
-endif # neq $(BASE_TYPE),importlib
-
-
-# Global targets
-.PHONY:: $(ALLTARGET)
-$(ALLTARGET):: $(RELEASABLES)
-TARGET:: $(RELEASABLES)
-
-ifeq ($(TARGET_$(call sanitise,$(IMPORTLIBTARGET))),1)
-  LIBRARY:: $(IMPORTLIBTARGET)
-else
-  ifeq ($(BASE_TYPE),staticlib)
-    LIBRARY:: $(BINTARGET)
-  endif
-endif
-
-
-# Deal with test code batch files generation.
-ifneq ($(TESTPATH),)
-  EPOC_ROOT:=$(patsubst %/,%,$(EPOCROOT))
-  TOBLDINF:=$(dir $(subst :,,$(subst $(EPOC_ROOT)/,,$(COMPONENT_META))))
-
-
-  BATCHDIR:=$(EPOCROOT)/epoc32/release/$(VARIANTPLATFORM)/$(VARIANTTYPE)/z/test/
-  $(eval $(call MakeTestBatchFiles,$(TARGET),$(BATCHDIR)$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH)))
-  BATCHFILE_CREATED_$(BATCHDIR)$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH):=1
-  TARGET_CREATED_$(EPOCROOT)/epoc32/release/$(VARIANTPLATFORM)/$(VARIANTTYPE)/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH)_$(TARGET):=1
-  RELEASABLES:=$(RELEASABLES) $(EPOCROOT)/epoc32/release/$(VARIANTPLATFORM)/$(VARIANTTYPE)/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH)
-  CLEANTARGETS:=$(CLEANTARGETS) $(EPOCROOT)/epoc32/release/$(VARIANTPLATFORM)/$(VARIANTTYPE)/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH)
-endif
-
-# clean up
-$(eval $(call GenerateStandardCleanTarget,$(CLEANTARGETS),$(CREATABLEPATHS),))
-# make the output directories while reading makefile - some build engines prefer this
-$(call makepath,$(CREATABLEPATHS))
-# for the abld -what target
-$(eval $(call whatmacro,$(RELEASABLES),WHATWINSCW))
+# 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:
+# WINSCW EXE/DLL/IMPLIB/LIB Function Like Makefile (FLM)
+# Knows how to build all possible executables for the WINSCW emulator build
+#
+#
+
+# passed in values, stripped of whitespace
+COPY_FOR_STATIC_LINKAGE:=$(strip $(COPY_FOR_STATIC_LINKAGE))
+DEFFILE:=$(strip $(DEFFILE))
+DEFFILEKEYWORD:=$(strip $(DEFFILEKEYWORD))
+EPOCALLOWDLLDATA:=$(strip $(EPOCALLOWDLLDATA))
+EXPORTLIBRARY:=$(strip $(EXPORTLIBRARY))
+BASEADDRESS:=$(strip $(BASEADDRESS))
+LINKAS:=$(strip $(LINKAS))
+NOEXPORTLIBRARY:=$(strip $(NOEXPORTLIBRARY))
+SECUREID:=$(strip $(SECUREID))
+UID2:=$(strip $(UID2))
+UID3:=$(strip $(UID3))
+VENDORID:=$(strip $(VENDORID))
+VID:=$(strip $(VID))
+WIN32_HEADERS:=$(strip $(WIN32_HEADERS))
+
+# local variables
+BINDIR:=
+BINDIRSTATICLINK:=
+BINTARGET:=
+BINTARGETSTATICLINK:=
+BLDDIR:=
+CHECKLIB_TYPE:=
+CREATABLEPATHS:=
+CLEANTARGETS:=
+CW_RUNTIME:=
+ENTRYSYMBOL:=
+IMPORTLIBLINKAS:=
+IMPORTLIBTARGET:=
+LIBDIR:=
+LINKER_FIRSTSTATLIB:=
+MAINLINKAS:=
+NEWLIBFILE:=
+RELEASABLES:=
+TC_RELEASABLES:=
+STATLIBDIR:=
+STDCPP_BUILD:=
+STDCPPTAGFILE:=
+UID1:=
+WIN32_LIBRARIES:=
+
+# FIVESPACES variable created to ensure that a suitable gap of space characters can
+# be placed between the separate arguments in the call to a tool (if required).
+# This is a workaround for a problem in Cygwin, where separate arguments are interpreted
+# as a single argument when passed to bash.
+FIVESPACES=$(BLANK)     $(BLANK)
+
+# CW runtime varies based on TARGETTYPE requirements, with wrapper FLMs dictating the choice
+# We override a CW-specific environment variable to do this, in common with ABLD
+ifeq ($(CW_STATIC_RUNTIME),1)
+  CW_RUNTIME:=$(CW_RUNTIME_STATIC)
+  CFLAGS:=$(CFLAGS) $(OPT.RUNTIME)staticmulti
+else
+  CW_RUNTIME:=$(CW_RUNTIME_NONSTATIC)
+  CFLAGS:=$(CFLAGS) $(OPT.RUNTIME)dllmulti
+endif
+MWSym2LibraryFiles:=$(subst $(CHAR_SPACE),$(DIRSEP),$(CW_RUNTIME) $(CW_DEFAULT_LIBS))
+ifneq ($(WIN32_LIBRARY),)
+  WIN32_HEADERS:=1
+  WIN32_LIBRARIES:=$(addprefix $(OPT.LIBFILE),$(WIN32_LIBRARY))
+endif
+
+# top-level definitions
+BINDIR:=$(RELEASEPATH)/$(FULLVARIANTPATH)
+
+# TARGETPATH and COPY_FOR_STATIC_LINKAGE only apply when TARGETPATH is a sub-directory of /sys/bin
+TARGETPATH_APPEND:=$(subst \,/,$(TARGETPATH))
+ifneq ($(findstring /sys/bin/,$(TARGETPATH_APPEND)),)
+  ifeq ($(COPY_FOR_STATIC_LINKAGE),1)
+    BINDIRSTATICLINK:=$(BINDIR)
+  endif
+  BINDIR:=$(BINDIR)/z$(TARGETPATH_APPEND)
+else
+  COPY_FOR_STATIC_LINKAGE:=0
+endif
+
+BLDDIR:=$(OUTPUTPATH)/$(FULLVARIANTPATH)
+LIBDIR:=$(RELEASEPATH)/$(LINKPATH)
+STATLIBDIR:=$(RELEASEPATH)/$(FULLVARIANTPATH)
+CREATABLEPATHS:=$(BLDDIR) $(BINDIR) $(BINDIRSTATICLINK)
+
+# Deduce whether we should be performing a build with standard CPP characteristics
+# This operates differently per-OS release, although OE TARGETTYPEs always build with standard CPP traits
+ifeq ($(OPEN_ENVIRONMENT),1)
+  STDCPP_BUILD:=1
+endif
+
+ifeq ($(SUPPORTS_STDCPP_NEWLIB),1)
+  ifeq ($(NOSTDCPP),1)
+    STDCPP_BUILD:=
+  else
+    ifeq ($(STDCPP),1)
+      STDCPP_BUILD:=1
+    endif
+  endif
+
+  # Operator new linking depends on both the use of the NEWLIB keyword and whether a component supports a standard
+  # CPP build.
+  ifneq ($(NEWLIB),)
+    # If specified, always use the NEWLIB keyword value for operator new library linking
+    NEWLIBFILE:=$(STATLIBDIR)/$(NEWLIB)
+  else
+    # If not performing a standard CPP build, link to an appropriate default Symbian new library.
+    # Standard CPP components defer to the toolchain supplied libraries.
+    ifneq ($(STDCPP_BUILD),1)
+      ifeq ($(SYSTEM_TARGET),1)
+        NEWLIBFILE:=$(STATLIBDIR)/$(DEFAULT_SYSTEM_NEWLIB)
+      else
+        NEWLIBFILE:=$(STATLIBDIR)/$(DEFAULT_NORMAL_NEWLIB)
+      endif
+    endif
+  endif
+endif
+
+ifeq ($(STDCPP_BUILD),1)
+  CDEFS:=$(CDEFS) $(STDCPP_DEF)
+  SYSTEMINCLUDE:=$(SYSTEMINCLUDE) $(STDCPP_INCLUDE)
+  CFLAGS:=$(CFLAGS) $(OPT.WCHAR) on
+  CHECKLIB_TYPE:=$(OPT.CHECKLIB.STDCPP)
+  STDCPPTAGFILE:=$(OPT.LIBPATH)$(EPOCROOT)/epoc32/tools/tag $(OPT.SEARCH) tag_coff
+else
+  CFLAGS:=$(CFLAGS) $(OPT.WCHAR) off
+  CHECKLIB_TYPE:=$(OPT.CHECKLIB.SYMCPP)
+endif
+
+ifeq ($(WIN32_HEADERS),1)
+  CDEFS:=$(CDEFS) WIN32
+  CDEFS:=$(CDEFS) _WINDOWS
+  CFLAGS:=$(CFLAGS) $(OPT.STDINC)
+else
+  CFLAGS:=$(CFLAGS) $(OPT.NOSTDINC)
+endif
+
+# get the compiler to generate dependencies for us?
+ifeq ($(NO_DEPEND_GENERATE),)
+  CFLAGS:=$(CFLAGS) $(OPT.DEPEND)
+endif
+
+# specifics relating to the base type of the target being processed
+ifeq ($(BASE_TYPE),dll)
+  # Special case, although this should be dealt with in the wrapper FLM in a better way
+  ifeq ($(TARGETTYPE),exexp)
+    CDEFS:=$(CDEFS) __EXE__
+    ENTRYSYMBOL:=__E32Startup
+    LFLAGS:=$(LFLAGS) $(OPT.NOENTRY)
+    UID1:=1000007a
+  else
+    CDEFS:=$(CDEFS) __DLL__
+    ENTRYSYMBOL:=__E32Dll
+    LFLAGS:=$(LFLAGS) $(OPT.MAINENTRYPOINT)__Win32DllMain@12
+    UID1:=10000079
+  endif
+  LFLAGS:=$(LFLAGS) $(OPT.SHARED)
+
+  ifneq ($(BASEADDRESS),)
+    LFLAGS:=$(LFLAGS) $(OPT.IMAGEBASE)$(BASEADDRESS)
+  endif
+
+  ifeq ($(FIRST_STATLIB),)
+    BASE_TYPE_STATLIB:=edll.lib
+  else
+    BASE_TYPE_STATLIB:=$(FIRST_STATLIB)
+  endif
+endif
+ifeq ($(BASE_TYPE),exe)
+  CDEFS:=$(CDEFS) __EXE__
+  ENTRYSYMBOL:=?_E32Bootstrap@@YGXXZ
+  UID1:=1000007a
+
+  ifeq ($(FIRST_STATLIB),)
+    BASE_TYPE_STATLIB:=eexe.lib
+  else
+    BASE_TYPE_STATLIB:=$(FIRST_STATLIB)
+  endif
+endif
+
+ifeq ($(FIRSTLIB),)
+  LINKER_FIRSTSTATLIB:=$(BASE_TYPE_STATLIB)
+else
+  LINKER_FIRSTSTATLIB:=$(FIRSTLIB)
+endif
+
+
+TARGETEXT:=$(if $(REQUESTEDTARGETEXT),$(REQUESTEDTARGETEXT),$(TARGETTYPE))
+BINTARGET:=$(BINDIR)/$(TARGET).$(TARGETEXT)
+
+
+# Run trace compiler #####################################
+TRACE_MARKER_PATH:=$(OUTPUTPATH)
+
+ifeq ($(subst 0,,$(UID3)),)
+  ifeq ($(UID2),)
+    USE_TRACE_COMPILER:=
+  else
+    UID_TC:=$(UID2)
+  endif
+else
+  UID_TC:=$(UID3)
+endif
+
+# USE_TRACE_COMPILER defaults to blank in Raptor config.
+# Users can turn TC on by setting it to 1 in user config.
+ifneq ($(USE_TRACE_COMPILER),)
+  # TARGETEXT must be set before here
+  include $(FLMHOME)/tracecompiler.mk
+  TC_RELEASABLES:=$(TRACE_DICTIONARY) $(AUTOGEN_HEADER)
+endif
+
+
+####################
+## IMPORT LIBRARY ##
+####################
+
+IMPORTLIBLINKAS:=$(TARGET).$(TARGETEXT)
+# LINKAS, if supplied, only applies to IMPLIB TARGETTYPEs
+ifeq ($(BASE_TYPE),importlib)
+  ifneq ($(LINKAS),)
+    IMPORTLIBLINKAS:=$(LINKAS)
+  else
+    IMPORTLIBLINKAS:=$(TARGET).dll
+  endif
+endif
+
+ifneq ($(EXPORTLIBRARY),)
+  IMPORTLIBTARGET:=$(LIBDIR)/$(EXPORTLIBRARY).lib
+else
+  IMPORTLIBTARGET:=$(LIBDIR)/$(TARGET).lib
+endif
+
+# Regardless of whether a TARGETTYPE normally supports an import library, always attempt
+# to generate one if an explicit DEFFILE keyword was listed
+ifeq ($(DEFFILEKEYWORD),1)
+  SUPPORTS_IMPORT_LIBRARY:=1
+endif
+
+ifeq ($(SUPPORTS_IMPORT_LIBRARY),1)
+  ifneq ($(NOEXPORTLIBRARY),1)
+    ifneq ($(TARGET_$(call sanitise,$(IMPORTLIBTARGET))),1)
+      RELEASABLES:=$(RELEASABLES) $(if $(or $(EXPORTUNFROZEN),$(DEFFILE)),$(IMPORTLIBTARGET))
+
+      # import libraries are generated to the UDEB release directory
+      ifneq ($(VARIANTTYPE),udeb)
+        CREATABLEPATHS:=$(CREATABLEPATHS) $(if $(or $(EXPORTUNFROZEN),$(DEFFILE)),$(LIBDIR))
+      endif
+
+      ifneq ($(EXPORTUNFROZEN),)
+        # EXPORTUNFROZEN amounts to doing the stage-two link with the makedef generated temporary .def file but creating a .lib
+        # file as a side-effect of linking.  The import library is therefore dependent on the final binary in this instance.
+        $(info <warning project='$(PROJECT_META)' component='$(COMPONENT_META)'>EXPORTUNFROZEN present in $(PROJECT_META) - unfrozen exports will be represented in import library.</warning> )
+        $(IMPORTLIBTARGET): $(BINTARGET)
+        $(eval TARGET_$(call sanitise,$(IMPORTLIBTARGET)):=1)
+      else
+        ifneq ($(DEFFILE),)
+          # If a .def file physically exists (either explicitly via DEFFILE or implicitly in the correct place) then we
+          # generate an import library with reference to it
+          PREPPEDDEFFILE:=$(BLDDIR)/$(TARGET).prep.def
+          CLEANTARGETS:=$(CLEANTARGETS) $(PREPPEDDEFFILE)
+
+          define win32def2lib
+            $(IMPORTLIBTARGET): $(DEFFILE)
+	          $(call startrule,win32def2lib) \
+	          $(PREPDEF) "$(DEFFILE)" "$(PREPPEDDEFFILE)" && \
+	          $(LD) $(PREPPEDDEFFILE) $(OPT.IMPORTLIB) -o "$$@" $(OPT.ADDCOMMAND) "out:$(IMPORTLIBLINKAS)" $(OPT.WARNINGS) off \
+	          $(call endrule,win32def2lib)
+          endef
+          $(eval $(win32def2lib))
+          $(eval TARGET_$(call sanitise,$(IMPORTLIBTARGET)):=1)
+        endif
+      endif
+    endif
+  endif
+endif
+
+
+ifneq ($(BASE_TYPE),importlib)
+
+  #############
+  ## COMPILE ##
+  #############
+
+  ifeq ($(COPY_FOR_STATIC_LINKAGE),1)
+    BINTARGETSTATICLINK:=$(BINDIRSTATICLINK)/$(TARGET).$(TARGETEXT)
+  endif
+
+  RELEASABLES:=$(RELEASABLES) $(BINTARGET) $(BINTARGETSTATICLINK)
+
+  # work on a local source files list
+  SRCFILES:=$(SOURCE)
+  # and there may be more source for stage 2 in OE builds
+  SRCFILES_OE:=
+
+  ifneq ($(BASE_TYPE),staticlib)
+    # add the generated UID source file
+    GENSOURCE:=$(BLDDIR)/$(TARGET).UID.CPP
+    SRCFILES:=$(SRCFILES) $(GENSOURCE)
+
+    # the generated symbol lookup source file for Open Environment.
+    # this only gets linked in at stage 2
+    SYMSOURCE:=$(if $(OPEN_ENVIRONMENT),$(BLDDIR)/$(TARGET)_SYM_.cpp,)
+    SRCFILES_OE:=$(SYMSOURCE)
+
+    CLEANTARGETS:=$(CLEANTARGETS) $(GENSOURCE) $(SYMSOURCE)
+
+    ifeq ($(UID2),00000000)
+      ifneq ($(UID2_DEFAULT),)
+        UID2:=$(UID2_DEFAULT)
+      endif
+    endif
+
+    ifeq ($(SECUREID),)
+      SECUREID:=$(UID3)
+    endif
+
+    define win32generateUIDcpp
+      $(GENSOURCE): $(PROJECT_META)
+	    $(call startrule,win32generateUIDcpp,,) \
+	    echo "// SBS-generated uid source file" > $$@ && \
+	    echo "#include <e32cmn.h>" >> $$@ && \
+	    echo "#pragma data_seg(\".SYMBIAN\")" >> $$@ && \
+	    echo "__EMULATOR_IMAGE_HEADER2(0x$(UID1),0x$(UID2),0x$(UID3),EPriority$(EPOCPROCESSPRIORITY),0x$(CAPABILITYFLAG1),0x$(CAPABILITYFLAG2),0x$(SECUREID),0x$(VENDORID),0x$(VERSIONHEX),$(EPOCALLOWDLLDATA))" >> $$@ && \
+	    echo "#pragma data_seg()" >> $$@ \
+	    $(call endrule,win32generateUIDcpp)
+    endef
+    $(eval $(win32generateUIDcpp))
+  endif # neq $(BASE_TYPE),staticlib
+
+  # object files
+  OBJECTFILES:=$(patsubst %,$(BLDDIR)/%,$(addsuffix .o,$(basename $(notdir $(call allsuffixsubst,.cia .CIA .Cia,_.cia,$(SRCFILES))))))
+  OBJECTFILES:=$(patsubst %.UID.o,%_UID_.o,$(OBJECTFILES))
+
+  # object file extras for stage 2
+  OBJECTFILES_OE:=$(patsubst %,$(BLDDIR)/%,$(addsuffix .o,$(basename $(notdir $(SRCFILES_OE)))))
+
+  CLEANTARGETS:=$(CLEANTARGETS) $(OBJECTFILES) $(OBJECTFILES_OE)
+
+  # include paths and preinclude file
+  UINCLUDE:=$(patsubst %,$(OPT.USERINCLUDE)%,$(USERINCLUDE))
+  SINCLUDE:=$(patsubst %,$(OPT.SYSINCLUDE)%,$(SYSTEMINCLUDE))
+  PINCLUDE:=$(OPT.PREINCLUDE)$(notdir $(PRODUCT_INCLUDE))
+
+  #INCLUDES:=$(UINCLUDE) $(OPT.SPLITINCLUDE) $(SINCLUDE) $(PINCLUDE)
+  INCLUDES:=$(OPT.SPLITINCLUDE) $(UINCLUDE) $(SINCLUDE) $(PINCLUDE)
+
+  # macro definitions
+  DEFINES:=$(call makemacrodef,$(OPT.DEFINE),$(CDEFS) $(TARGET_MACRO))
+
+
+  # $(1) is the name of the source file, $(2) is the extension to map it to e.g. .o
+  # no space in front of function body
+  define mapwin32file
+    $(patsubst %.UID$(2),%_UID_$(2),$(BLDDIR)/$(addsuffix $2,$(basename $(notdir $(call allsuffixsubst,.cia .CIA .Cia,_.cia,$(1))))))
+  endef
+
+  # compile all source files, creating and including compiler generated dependency files along the way
+  # SED is used to (a) remove relatively pathed "object_file: source_file" references that can appear
+  # with some versions of mwccsym2 and (b) convert slashes
+  define win32compile2object
+
+    $(eval DEPENDFILENAME:=$(call mapwin32file,$(1),.o.d))
+    $(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
+
+    $(call mapwin32file,$(1),.o): $(1) $(PROJECT_META) $(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT) | $(if $(USE_TRACE_COMPILER),$(TRACE_MARKER))
+	  $(call startrule,win32compile2object,,$(1)) \
+	  $(CC) $$(if $$(filter %.C,$(1)),-lang c) $(CFLAGS) $(OPTION_CW) \
+	  $(if $(STDCPP_BUILD),$$(if $$(filter %.c %.C,$(1)),,$$(call makemacrodef,$(OPT.DEFINE),$(STDCPP_WCHAR_DEF))),) \
+	  $(DEFINES) $(INCLUDES) $(OPT.OUT)"$$@" "$(1)" \
+	  $(if $(NO_DEPEND_GENERATE),,&& $(GNUSED) 's#\\\\\(.\)#/\1#g;s#/ #\\\ #g;s#\([A-Za-z]:\)\\\\#\1/#g;1,1s#.*: .* \(.\)\?$$$$#$(call mapwin32file,$(1),.o): $1 \1#' $(call mapwin32file,$(1),.dep) > $(call mapwin32file,$(1),.o.d)) \
+	  $(call endrule,win32compile2object)
+
+    ifeq ($(NO_DEPEND_GENERATE),)
+      CLEANTARGETS:=$$(CLEANTARGETS) $(call mapwin32file,$(1),.dep) $(DEPENDFILENAME)
+    endif
+    
+    ifneq ($(DEPENDFILE),)
+      ifeq ($(NO_DEPEND_INCLUDE),)
+        ifeq ($(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS))),)
+          -include $(DEPENDFILE)
+        endif
+      endif
+    endif
+
+    # individual source file compilation
+    SOURCETARGET_$(call sanitise,$(1)): $(call mapwin32file,$(1),.o)
+
+  endef
+
+  # List target, depends on object file
+  define win32list
+  LISTING:: $(OBJECTFILES) $(OBJECTFILES_OE)
+	$(call startrule,win32listing) \
+	$(CC) $(OPT.LISTING) $(patsubst %.UID.o,%_UID_.o,$(BLDDIR)/$(addsuffix .o,$(basename $(notdir $(1))))) -o $(basename $1).WINSCW.lst \
+	$(call endrule,win32listing)
+  endef
+
+  $(foreach SRCFILE,$(SRCFILES) $(SRCFILES_OE),$(eval $(call win32compile2object,$(SRCFILE))))
+  $(foreach SRCFILE,$(SRCFILES) $(SRCFILES_OE),$(eval $(call win32list,$(SRCFILE))))
+
+  ######################
+  ## RESOURCE COMPILE ##
+  ######################
+
+  # If Python has been used to construct the environment on Windows then the standard MW include path environment
+  # variable will have been munged to UPPERCASE.
+  STDMWCINCLUDEPATHS:=$(if $(MWCSym2Includes),$(MWCSym2Includes),$(MWCSYM2INCLUDES))
+
+  define win32resourcecompile
+    # Note that, if dependency files are required, two calls are made to the resource compiler here.
+    # There seems to be no means to override the default behaviour of dumping dependency files into the CWD when using -MD.
+    # So - we compile once for real, and then pipe dependency output through SED afterwards to create the dependency file where we want it
+
+    $(eval DEPENDFILENAME:=$(call mapwin32file,$(1),.res.d))
+    $(eval DEPENDFILE:=$(wildcard $(DEPENDFILENAME)))
+
+    $(call mapwin32file,$(1),.res): $(1) $(PROJECT_META) $(if $(DEPENDFILE),,RESOURCE BITMAP EXPORT)
+	  $(call startrule,win32resourcecompile,,$(1)) \
+	  MWCIncludes='$(STDMWCINCLUDEPATHS)' $(RC) $(OPT.OUT)"$$@" "$(1)" \
+	  $(if $(NO_DEPEND_GENERATE),,&& \
+	    MWCIncludes='$(STDMWCINCLUDEPATHS)' $(RC) -make $(OPT.OUT)"$$@" "$(1)" | \
+	    $(GNUSED) 's#\\\\\(.\)#/\1#g;s#/ #\\\ #g;s#\([A-Za-z]:\)\\\\#\1/#g;1,1s#.*: .* \(.\)\?$$$$#$(call mapwin32file,$(1),.res): $1 \1#' > $(call mapwin32file,$(1),.res.d)) \
+	  $(call endrule,win32resourcecompile)
+
+    ifeq ($(NO_DEPEND_GENERATE),)
+      CLEANTARGETS:=$$(CLEANTARGETS) $(DEPENDFILENAME)
+    endif
+    
+    ifneq ($(DEPENDFILE),)
+      ifeq ($(NO_DEPEND_INCLUDE),)
+        ifeq ($(filter %CLEAN,$(call uppercase,$(MAKECMDGOALS))),)
+          -include $(DEPENDFILE)
+        endif
+      endif
+    endif
+
+  endef
+
+  $(foreach WIN32RESOURCEFILE,$(WIN32_RESOURCE),$(eval $(call win32resourcecompile,$(WIN32RESOURCEFILE))))
+  OBJECTFILES:=$(OBJECTFILES) $(patsubst %,$(BLDDIR)/%,$(addsuffix .res,$(basename $(notdir $(WIN32_RESOURCE)))))
+
+  ##################
+  ## LINK/ARCHIVE ##
+  ##################
+
+  # libraries
+  STATICLIBS:=$(patsubst %,%.lib,$(STATICLIBRARY))
+  STATICLIBFILES:=$(patsubst %,$(STATLIBDIR)/%,$(STATICLIBS))
+  LINKER_FIRSTSTATLIBFILE:=$(STATLIBDIR)/$(LINKER_FIRSTSTATLIB)
+
+  ifeq ($(VARIANTTYPE),urel)
+    LINKLIBS:=$(patsubst %.dso,%.lib,$(LIBRARY))
+  else
+    LINKLIBS:=$(patsubst %.dso,%.lib,$(LIBRARY_DEBUG))
+  endif
+
+  LINKLIBFILES:=$(patsubst %,$(LIBDIR)/%,$(LINKLIBS))
+
+  MAP:=
+  ifneq ($(BASE_TYPE),staticlib)
+    ifneq ($(BASE_TYPE),importlib)
+      # link map file (urel only)
+      ifeq ($(VARIANTTYPE),urel)
+        MAP:=$(OPT.MAP)$(BINTARGET).map
+        RELEASABLES:=$(RELEASABLES) $(BINTARGET).map
+      endif
+    endif
+  endif
+
+  # all object files are listed in a response file to minimise the length of linker calls
+  OBJECTFILES_LRF:=$(BLDDIR)/$(TARGET)_$(VARIANTTYPE)_objects.lrf
+  CLEANTARGET:=$(CLEANTARGETS) $(OBJECTFILES_LRF)
+
+  define groupin10
+	$(if $1,@echo -e $(foreach L,$(wordlist 1,10,$1),"$(L)\\n") >> $(OBJECTFILES_LRF),)
+	$(if $1,$(call groupin10,$(wordlist 11,$(words $1),$1)),@true)
+  endef
+
+  #
+  # Archive
+  #
+  ifeq ($(BASE_TYPE),staticlib)
+    define win32archive
+      $(BINTARGET): $(OBJECTFILES)
+	    @echo "" > $(OBJECTFILES_LRF);
+		$(call groupin10,$(notdir $(OBJECTFILES))) ;
+	    $(call startrule,win32archive) \
+	    $(LD) $(OPT.STATICLIBRARY) $(LFLAGS) $(OPT.NOIMPLIB) $(WIN32_LIBRARIES) $(OPT.OUT)"$$@" $(STDCPPTAGFILE) $(OPT.LIBPATH)$(BLDDIR) $(OPT.SEARCH) @$(OBJECTFILES_LRF) \
+	    $(if $(SAVESPACE),; $(GNURM) -rf $(BLDDIR); true,) \
+	    $(call endrule,win32archive)
+    endef
+    $(eval $(win32archive))
+  endif
+
+  ifneq ($(EPOCHEAPSIZEMIN_DEC_KB),)
+    LFLAGS:=$(LFLAGS) $(OPT.HEAPRESERVE)$(EPOCHEAPSIZEMAX_DEC_KB) $(OPT.HEAPCOMMIT)$(EPOCHEAPSIZEMIN_DEC_KB)
+  endif
+
+  #
+  # Simple link
+  #
+  ifeq ($(BASE_TYPE),exe)
+    define win32simplelink
+      $(BINTARGET).map: $(BINTARGET)
+
+      $(BINTARGET): $(OBJECTFILES) $(LINKER_FIRSTSTATLIBFILE) $(NEWLIBFILE) $(STATICLIBFILES) $(LINKLIBFILES)
+	    @echo "" > $(OBJECTFILES_LRF);
+		$(call groupin10,$(notdir $(OBJECTFILES))) ;
+	    $(call startrule,win32simplelink) \
+	    $(if $(SUPPORTS_STDCPP_NEWLIB),$(if $(STATICLIBFILES),$(CHECKLIB) $(CHECKLIB_TYPE) $(OPT.CHECKLIB.WIN32) $(STATICLIBFILES) &&,),) \
+	    MWSym2LibraryFiles="$(MWSym2LibraryFiles)" $(LD) $(LFLAGS) $(OPT.MENTRYPOINT)$(ENTRYSYMBOL) $(MAP) $(LINKER_FIRSTSTATLIBFILE) $(NEWLIBFILE) $(WIN32_LIBRARIES) $(STATICLIBFILES) $(LINKLIBFILES) $(OPT.OUT)"$$@" $(OPT.NOIMPLIB) $(OPT.LIBPATH)$(BLDDIR) $(OPT.SEARCH) @$(OBJECTFILES_LRF) \
+	    $(if $(SAVESPACE),; $(GNURM) -rf $(BLDDIR); true,) \
+	    $(call endrule,win32simplelink)
+    endef
+    $(eval $(win32simplelink))
+  endif
+
+  #
+  # Two stage link
+  #
+  ifeq ($(BASE_TYPE),dll)
+    TMP_IMPLIB:=$(BLDDIR)/$(TARGET).lib
+    TMP_INFFILE:=$(BLDDIR)/$(TARGET).inf
+    TMP_SYMFILE:=$(if $(OPEN_ENVIRONMENT),$(BLDDIR)/$(TARGET).sym,)
+    TMP_TARGET:=$(BLDDIR)/$(TARGET).$(TARGETEXT)
+    TMP_DEFFILE:=$(BLDDIR)/$(TARGET).def
+
+    CLEANTARGETS:=$(CLEANTARGETS) $(TMP_IMPLIB) $(TMP_INFFILE) $(TMP_TARGET) $(TMP_DEFFILE) $(TMP_SYMFILE)
+
+    MAKEDEF_ARGS:=-absent $(ENTRYSYMBOL) -Inffile  $(call dblquote,$(TMP_INFFILE)) $(NAME_LOOKUP)
+
+    ifeq ($(SYSTEM_TARGET),1)
+        MAKEDEF_ARGS:=$(MAKEDEF_ARGS) -SystemTargetType
+    endif
+
+    ifneq ($(FIXED_EXPORT),)
+      # Fixed export TARGETTYPE, but with possibility of a .def file if explicitly specified and available
+      ifeq ($(DEFFILEKEYWORD),1)
+        ifneq ($(DEFFILE),)
+          MAKEDEF_ARGS:=$(MAKEDEF_ARGS) -Frzfile $(call dblquote,$(DEFFILE))
+        endif
+      endif
+      MAKEDEF_ARGS:=$(MAKEDEF_ARGS) -1 $(FIXED_EXPORT)
+    else
+      # Variable export TARGETTYPE with either deduced or explicitly specified .def file (if available)
+      ifneq ($(DEFFILE),)
+        MAKEDEF_ARGS:=$(MAKEDEF_ARGS) -Frzfile $(call dblquote,$(DEFFILE))
+      endif
+    endif
+
+
+    ifneq ($(EXPORTSUNFROZEN),)
+    	LIBRARY: $(TMP_IMPLIB)
+    endif
+
+    define win32stageonelink
+      # Stage One
+      # Link by name, generating temporary main binary and import library.
+      $(TMP_IMPLIB): $(TMP_TARGET)
+
+      $(TMP_TARGET): $(OBJECTFILES) $(LINKER_FIRSTSTATLIBFILE) $(NEWLIBFILE) $(STATICLIBFILES) $(LINKLIBFILES)
+	    @echo "" > $(OBJECTFILES_LRF);
+		$(call groupin10,$(notdir $(OBJECTFILES))) ;
+	    $(call startrule,win32stageonelink) \
+	    $(if $(SUPPORTS_STDCPP_NEWLIB),$(if $(STATICLIBFILES),$(CHECKLIB) $(CHECKLIB_TYPE) $(OPT.CHECKLIB.WIN32) $(STATICLIBFILES) &&,),) \
+	    MWSym2LibraryFiles="$(MWSym2LibraryFiles)" $(LD) $(LFLAGS) $(OPT.MENTRYPOINT)$(ENTRYSYMBOL) $(OPT.EXPORT)$(EXPORT_TYPE) $(OPT.NOCOMPACTIMPORTLIB) $(OPT.ADDCOMMAND) "out:$(TARGET).$(TARGETEXT)" $(OPT.WARNINGS) off $(OPT.IMPLIB)"$(TMP_IMPLIB)" $(OPT.OUT)"$(TMP_TARGET)" $(LINKER_FIRSTSTATLIBFILE) $(NEWLIBFILE) $(WIN32_LIBRARIES) $(STATICLIBFILES) $(LINKLIBFILES) $(OPT.LIBPATH)$(BLDDIR) $(OPT.SEARCH) @$(OBJECTFILES_LRF) \
+	    $(call endrule,win32stageonelink)
+    endef
+    $(eval $(win32stageonelink))
+
+    define win32processexports
+      # Process exports
+      # Generate a descriptive info file from the import library.
+      # Push info file through MAKEDEF to generated a valid .def file for link by ordinal.
+      $(TMP_DEFFILE): $(TMP_IMPLIB)
+	    $(call startrule,win32processexports) \
+	    $(LD) $(LFLAGS_INFGEN) $(OPT.OUT)"$(TMP_INFFILE)" "$(TMP_IMPLIB)" && \
+	    $(MAKEDEF) $(MAKEDEF_ARGS) "$$@" \
+	    $(call endrule,win32processexports)
+    endef
+    $(eval $(win32processexports))
+
+    ifeq ($(OPEN_ENVIRONMENT),1)
+      define win32processoeexports
+   	    # Process additional exports for Open Environment
+        # Generate a symbol file from the temporary DLL.
+        # Generate a C++ source file from the symbol file
+
+        $(TMP_SYMFILE): $(TMP_TARGET)
+	      $(call startrule,win32generatesymfile) \
+	      $(LD) $(LFLAGS_SYMGEN) $(OPT.OUT)"$(TMP_SYMFILE)" "$(TMP_TARGET)" \
+	      $(call endrule,win32generatesymfile)
+
+        $(SYMSOURCE): $(TMP_SYMFILE)
+	      $(call startrule,win32generatesymcpp) \
+	      $(SYMLOOKUPUTIL) $(OPT.OUT)"$(SYMSOURCE)" $(OPT.SYM)"$(TMP_SYMFILE)" $(SYMLOOKUPARGS) \
+	      $(call endrule,win32generatesymcpp)
+      endef
+      $(eval $(win32processoeexports))
+    endif
+
+    define win32stagetwolink
+      # Stage Two
+      # Link by ordinal, based on a previously MAKEDEF-generated temporary .def file
+      # Optionally create an import library if EXPORTUNFROZEN is specified
+      #
+      $(BINTARGET).map: $(BINTARGET)
+
+      $(BINTARGET): $(OBJECTFILES) $(OBJECTFILES_OE) $(LINKER_FIRSTSTATLIBFILE) $(STATICLIBFILES) $(NEWLIBFILE) $(LINKLIBFILES) $(TMP_DEFFILE)
+	    @echo "" > $(OBJECTFILES_LRF);
+		$(call groupin10,$(notdir $(OBJECTFILES) $(OBJECTFILES_OE))) ;
+	    $(call startrule,win32stagetwolink) \
+	    MWSym2LibraryFiles="$(MWSym2LibraryFiles)" \
+	    $(LD) $(LFLAGS) $(OPT.DEFFILE)$(TMP_DEFFILE) $(MAP) $(LINKER_FIRSTSTATLIBFILE) $(NEWLIBFILE) $(WIN32_LIBRARIES) $(STATICLIBFILES) $(LINKLIBFILES) \
+	    $(OPT.OUT)"$$@" \
+	    $(if $(EXPORTUNFROZEN),$(OPT.IMPLIB)$(IMPORTLIBTARGET),$(OPT.NOIMPLIB)) \
+	    $(OPT.LIBPATH)$(BLDDIR) $(OPT.SEARCH) @$(OBJECTFILES_LRF) \
+	    $(if $(SAVESPACE),; $(GNURM) -rf $(BLDDIR); true,) \
+	    $(call endrule,win32stagetwolink)
+    endef
+    $(eval $(win32stagetwolink))
+
+    define win32copyforstaticlink
+      # Copy additonal binary to "traditional" output location (if required)
+      $(BINTARGETSTATICLINK): $(BINTARGET)
+	    $(call startrule,win32copyforstaticlink) \
+	    $(GNUCP) $$< $$@ \
+	    $(call endrule,win32copyforstaticlink)
+    endef
+    ifeq ($(COPY_FOR_STATIC_LINKAGE),1)
+      $(eval $(win32copyforstaticlink))
+    endif
+
+    define e32freeze
+      # DLL-type targets that support import library generation support freezing of exports using EFREEZE
+      FREEZE:: $(1)
+	    $(call startrule,freeze,,$(RESOLVED_DEFFILE)) \
+	    $(EFREEZE) $(EFREEZE_REMOVE_OPTION) "$(RESOLVED_DEFFILE)" $(FIVESPACES) "$(2)" \
+	    $(call endrule,freeze)
+    endef
+    # Create only one freeze target per urel/udeb variant as the interface won't differ between them
+    # Only create a freeze target if the component supports import library generation
+    ifneq ($(TARGET_$(call sanitise,$(IMPORTLIBTARGET))_FREEZE),1)
+      ifeq ($(SUPPORTS_IMPORT_LIBRARY),1)
+        $(eval $(call e32freeze,$(BINTARGET),$(TMP_DEFFILE)))
+        $(eval TARGET_$(call sanitise,$(IMPORTLIBTARGET))_FREEZE:=1)
+      endif
+    endif
+  endif
+endif # neq $(BASE_TYPE),importlib
+
+
+# Global targets
+.PHONY:: $(ALLTARGET)
+$(ALLTARGET):: $(RELEASABLES)
+TARGET:: $(RELEASABLES)
+
+ifeq ($(TARGET_$(call sanitise,$(IMPORTLIBTARGET))),1)
+  LIBRARY:: $(IMPORTLIBTARGET)
+else
+  ifeq ($(BASE_TYPE),staticlib)
+    LIBRARY:: $(BINTARGET)
+  endif
+endif
+
+
+# Deal with test code batch files generation.
+ifneq ($(TESTPATH),)
+  EPOC_ROOT:=$(patsubst %/,%,$(EPOCROOT))
+  TOBLDINF:=$(dir $(subst :,,$(subst $(EPOC_ROOT)/,,$(COMPONENT_META))))
+
+
+  BATCHDIR:=$(EPOCROOT)/epoc32/release/$(VARIANTPLATFORM)/$(VARIANTTYPE)/z/test/
+  $(eval $(call MakeTestBatchFiles,$(TARGET),$(BATCHDIR)$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH)))
+  BATCHFILE_CREATED_$(BATCHDIR)$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH):=1
+  TARGET_CREATED_$(EPOCROOT)/epoc32/release/$(VARIANTPLATFORM)/$(VARIANTTYPE)/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH)_$(TARGET):=1
+  RELEASABLES:=$(RELEASABLES) $(EPOCROOT)/epoc32/release/$(VARIANTPLATFORM)/$(VARIANTTYPE)/z/test/$(MODULE)/$(VARIANTPLATFORM).$(TESTPATH)
+endif
+
+# clean up
+$(call raptor_clean,$(CLEANTARGETS))
+# make the output directories while reading makefile - some build engines prefer this
+$(call makepath,$(CREATABLEPATHS))
+# for the --what option and the log file
+$(call raptor_release,$(RELEASABLES) $(TC_RELEASABLES))
--- a/sbsv2/raptor/lib/flm/win32ani.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32ani.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,34 +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:
-# WINSCW ANI Function Like Makefile (FLM)
-# Build an emulator ANI
-# 
-#
-
-ifeq ($(TARGETTYPE),ani)
-
-BASE_TYPE:=dll
-CW_STATIC_RUNTIME:=1
-FIRST_STATLIB:=
-FIXED_EXPORT:=?CreateCAnimDllL@@YAPAVCAnimDll@@XZ
-SUPPORTS_IMPORT_LIBRARY:=0
-SYSTEM_TARGET:=0
-UID2_DEFAULT:=10003b22
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32ani.flm called with wrong TARGETTYPE (should be 'ani' but is '$(TARGETTYPE)'))
-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:
+# WINSCW ANI Function Like Makefile (FLM)
+# Build an emulator ANI
+# 
+#
+
+ifeq ($(TARGETTYPE),ani)
+
+BASE_TYPE:=dll
+CW_STATIC_RUNTIME:=1
+FIRST_STATLIB:=
+FIXED_EXPORT:=?CreateCAnimDllL@@YAPAVCAnimDll@@XZ
+SUPPORTS_IMPORT_LIBRARY:=0
+SYSTEM_TARGET:=0
+UID2_DEFAULT:=10003b22
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32ani.flm called with wrong TARGETTYPE (should be 'ani' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32bitmap.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32bitmap.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,22 +1,22 @@
-# 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:
-# Thin Function Like Makefile (FLM) wrapper to general resource building FLM
-# for win32 builds.
-# 
-#
-
-BINCOPYDIRS:=$(EPOCROOT)/epoc32/release/winscw/udeb $(EPOCROOT)/epoc32/release/winscw/urel
-
-# Main (and mostly generic) resource building FLM
-include $(FLMHOME)/bitmap.flm
+# 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:
+# Thin Function Like Makefile (FLM) wrapper to general resource building FLM
+# for win32 builds.
+# 
+#
+
+BINCOPYDIRS:=$(EPOCROOT)/epoc32/release/winscw/udeb $(EPOCROOT)/epoc32/release/winscw/urel
+
+# Main (and mostly generic) resource building FLM
+include $(FLMHOME)/bitmap.flm
--- a/sbsv2/raptor/lib/flm/win32dll.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32dll.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,34 +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:
-# WINSCW DLL Function Like Makefile (FLM)
-# Build an emulator DLL
-# 
-#
-
-ifeq ($(TARGETTYPE),dll)
-
-BASE_TYPE:=dll
-CW_STATIC_RUNTIME:=1
-FIRST_STATLIB:=
-FIXED_EXPORT:=
-SUPPORTS_IMPORT_LIBRARY:=1
-SYSTEM_TARGET:=0
-UID2_DEFAULT:=
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32dll.flm called with wrong TARGETTYPE (should be 'dll' but is '$(TARGETTYPE)'))
-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:
+# WINSCW DLL Function Like Makefile (FLM)
+# Build an emulator DLL
+# 
+#
+
+ifeq ($(TARGETTYPE),dll)
+
+BASE_TYPE:=dll
+CW_STATIC_RUNTIME:=1
+FIRST_STATLIB:=
+FIXED_EXPORT:=
+SUPPORTS_IMPORT_LIBRARY:=1
+SYSTEM_TARGET:=0
+UID2_DEFAULT:=
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error win32dll.flm called with wrong TARGETTYPE (should be 'dll' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32exe.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32exe.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,34 +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:
-# WINSCW EXE Function Like Makefile (FLM)
-# Build an emulator EXE
-# 
-#
-
-ifeq ($(TARGETTYPE),exe)
-
-BASE_TYPE:=exe
-CW_STATIC_RUNTIME:=1
-FIRST_STATLIB:=
-FIXED_EXPORT:=
-SUPPORTS_IMPORT_LIBRARY:=0
-SYSTEM_TARGET:=0
-UID2_DEFAULT:=
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32exe.flm called with wrong TARGETTYPE (should be 'exe' but is '$(TARGETTYPE)'))
-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:
+# WINSCW EXE Function Like Makefile (FLM)
+# Build an emulator EXE
+# 
+#
+
+ifeq ($(TARGETTYPE),exe)
+
+BASE_TYPE:=exe
+CW_STATIC_RUNTIME:=1
+FIRST_STATLIB:=
+FIXED_EXPORT:=
+SUPPORTS_IMPORT_LIBRARY:=0
+SYSTEM_TARGET:=0
+UID2_DEFAULT:=
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32exe.flm called with wrong TARGETTYPE (should be 'exe' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32exexp.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32exexp.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,34 +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:
-# WINSCW EXEXP Function Like Makefile (FLM)
-# Build an emulator EXEXP
-# 
-#
-
-ifeq ($(TARGETTYPE),exexp)
-
-BASE_TYPE:=dll
-CW_STATIC_RUNTIME:=1
-FIRST_STATLIB:=eexe.lib
-FIXED_EXPORT:=
-SUPPORTS_IMPORT_LIBRARY:=1
-SYSTEM_TARGET:=0
-UID2_DEFAULT:=
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32exexp.flm called with wrong TARGETTYPE (should be 'exexp' but is '$(TARGETTYPE)'))
-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:
+# WINSCW EXEXP Function Like Makefile (FLM)
+# Build an emulator EXEXP
+# 
+#
+
+ifeq ($(TARGETTYPE),exexp)
+
+BASE_TYPE:=dll
+CW_STATIC_RUNTIME:=1
+FIRST_STATLIB:=eexe.lib
+FIXED_EXPORT:=
+SUPPORTS_IMPORT_LIBRARY:=1
+SYSTEM_TARGET:=0
+UID2_DEFAULT:=
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32exexp.flm called with wrong TARGETTYPE (should be 'exexp' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32fsy.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32fsy.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,34 +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:
-# WINSCW FSY Function Like Makefile (FLM)
-# Build an emulator FSY
-# 
-#
-
-ifeq ($(TARGETTYPE),fsy)
-
-BASE_TYPE:=dll
-CW_STATIC_RUNTIME:=1
-FIRST_STATLIB:=
-FIXED_EXPORT:=CreateFileSystem
-SUPPORTS_IMPORT_LIBRARY:=0
-SYSTEM_TARGET:=0
-UID2_DEFAULT:=100039df
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32fsy.flm called with wrong TARGETTYPE (should be 'fsy' but is '$(TARGETTYPE)'))
-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:
+# WINSCW FSY Function Like Makefile (FLM)
+# Build an emulator FSY
+# 
+#
+
+ifeq ($(TARGETTYPE),fsy)
+
+BASE_TYPE:=dll
+CW_STATIC_RUNTIME:=1
+FIRST_STATLIB:=
+FIXED_EXPORT:=CreateFileSystem
+SUPPORTS_IMPORT_LIBRARY:=0
+SYSTEM_TARGET:=0
+UID2_DEFAULT:=100039df
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32fsy.flm called with wrong TARGETTYPE (should be 'fsy' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32implib.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32implib.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,31 +1,31 @@
-# 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:
-# WINSCW IMPLIB Function Like Makefile (FLM)
-# Build an emulator IMPLIB
-# 
-#
-
-ifeq ($(TARGETTYPE),implib)
-
-BASE_TYPE:=importlib
-CW_STATIC_RUNTIME:=0
-FIXED_EXPORT:=
-SUPPORTS_IMPORT_LIBRARY:=1
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32implib.flm called with wrong TARGETTYPE (should be 'implib' but is '$(TARGETTYPE)'))
-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:
+# WINSCW IMPLIB Function Like Makefile (FLM)
+# Build an emulator IMPLIB
+# 
+#
+
+ifeq ($(TARGETTYPE),implib)
+
+BASE_TYPE:=importlib
+CW_STATIC_RUNTIME:=0
+FIXED_EXPORT:=
+SUPPORTS_IMPORT_LIBRARY:=1
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32implib.flm called with wrong TARGETTYPE (should be 'implib' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32kdll.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32kdll.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,34 +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:
-# WINSCW KDLL Function Like Makefile (FLM)
-# Build an emulator KDLL
-# 
-#
-
-ifeq ($(TARGETTYPE),kdll)
-
-BASE_TYPE:=dll
-CW_STATIC_RUNTIME:=1
-FIRST_STATLIB:=ekll.lib
-FIXED_EXPORT:=
-SUPPORTS_IMPORT_LIBRARY:=1
-SYSTEM_TARGET:=1
-UID2_DEFAULT:=
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32kdll.flm called with wrong TARGETTYPE (should be 'dll' but is '$(TARGETTYPE)'))
-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:
+# WINSCW KDLL Function Like Makefile (FLM)
+# Build an emulator KDLL
+# 
+#
+
+ifeq ($(TARGETTYPE),kdll)
+
+BASE_TYPE:=dll
+CW_STATIC_RUNTIME:=1
+FIRST_STATLIB:=ekll.lib
+FIXED_EXPORT:=
+SUPPORTS_IMPORT_LIBRARY:=1
+SYSTEM_TARGET:=1
+UID2_DEFAULT:=
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32kdll.flm called with wrong TARGETTYPE (should be 'dll' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32kext.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32kext.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,34 +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:
-# WINSCW KEXT Function Like Makefile (FLM)
-# Build an emulator KEXT
-# 
-#
-
-ifeq ($(TARGETTYPE),kext)
-
-BASE_TYPE:=dll
-CW_STATIC_RUNTIME:=1
-FIRST_STATLIB:=eext.lib
-FIXED_EXPORT:=
-SUPPORTS_IMPORT_LIBRARY:=0
-SYSTEM_TARGET:=1
-UID2_DEFAULT:=
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32kext.flm called with wrong TARGETTYPE (should be 'kext' but is '$(TARGETTYPE)'))
-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:
+# WINSCW KEXT Function Like Makefile (FLM)
+# Build an emulator KEXT
+# 
+#
+
+ifeq ($(TARGETTYPE),kext)
+
+BASE_TYPE:=dll
+CW_STATIC_RUNTIME:=1
+FIRST_STATLIB:=eext.lib
+FIXED_EXPORT:=
+SUPPORTS_IMPORT_LIBRARY:=0
+SYSTEM_TARGET:=1
+UID2_DEFAULT:=
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32kext.flm called with wrong TARGETTYPE (should be 'kext' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32klib.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32klib.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,32 +1,32 @@
-# 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:
-# WINSCW KLIB Function Like Makefile (FLM)
-# Build an emulator KLIB
-# 
-#
-
-ifeq ($(TARGETTYPE),klib)
-
-BASE_TYPE:=staticlib
-CW_STATIC_RUNTIME:=1
-FIXED_EXPORT:=
-SUPPORTS_IMPORT_LIBRARY:=0
-SYSTEM_TARGET:=1
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32klib.flm called with wrong TARGETTYPE (should be 'klib' but is '$(TARGETTYPE)'))
-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:
+# WINSCW KLIB Function Like Makefile (FLM)
+# Build an emulator KLIB
+# 
+#
+
+ifeq ($(TARGETTYPE),klib)
+
+BASE_TYPE:=staticlib
+CW_STATIC_RUNTIME:=1
+FIXED_EXPORT:=
+SUPPORTS_IMPORT_LIBRARY:=0
+SYSTEM_TARGET:=1
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32klib.flm called with wrong TARGETTYPE (should be 'klib' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32ldd.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32ldd.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,34 +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:
-# WINSCW LDD Function Like Makefile (FLM)
-# Build an emulator LDD
-# 
-#
-
-ifeq ($(TARGETTYPE),ldd)
-
-BASE_TYPE:=dll
-CW_STATIC_RUNTIME:=1
-FIRST_STATLIB:=edev.lib
-FIXED_EXPORT:=?CreateLogicalDevice@@YAPAVDLogicalDevice@@XZ
-SUPPORTS_IMPORT_LIBRARY:=0
-SYSTEM_TARGET:=1
-UID2_DEFAULT:=100000af
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32ldd.flm called with wrong TARGETTYPE (should be 'ldd' but is '$(TARGETTYPE)'))
-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:
+# WINSCW LDD Function Like Makefile (FLM)
+# Build an emulator LDD
+# 
+#
+
+ifeq ($(TARGETTYPE),ldd)
+
+BASE_TYPE:=dll
+CW_STATIC_RUNTIME:=1
+FIRST_STATLIB:=edev.lib
+FIXED_EXPORT:=?CreateLogicalDevice@@YAPAVDLogicalDevice@@XZ
+SUPPORTS_IMPORT_LIBRARY:=0
+SYSTEM_TARGET:=1
+UID2_DEFAULT:=100000af
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32ldd.flm called with wrong TARGETTYPE (should be 'ldd' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32lib.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32lib.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,31 +1,31 @@
-# 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:
-# WINSCW Static Library Function Like Makefile (FLM)
-# Build an emulator LIB
-# 
-#
-
-ifeq ($(TARGETTYPE),lib)
-
-BASE_TYPE:=staticlib
-CW_STATIC_RUNTIME:=1
-FIXED_EXPORT:=
-SUPPORTS_IMPORT_LIBRARY:=0
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32lib.flm called with wrong TARGETTYPE (should be 'lib' but is '$(TARGETTYPE)'))
-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:
+# WINSCW Static Library Function Like Makefile (FLM)
+# Build an emulator LIB
+# 
+#
+
+ifeq ($(TARGETTYPE),lib)
+
+BASE_TYPE:=staticlib
+CW_STATIC_RUNTIME:=1
+FIXED_EXPORT:=
+SUPPORTS_IMPORT_LIBRARY:=0
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32lib.flm called with wrong TARGETTYPE (should be 'lib' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32pdd.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32pdd.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,34 +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:
-# WINSCW PDD Function Like Makefile (FLM)
-# Build an emulator PDD
-# 
-#
-
-ifeq ($(TARGETTYPE),pdd)
-
-BASE_TYPE=dll
-CW_STATIC_RUNTIME:=1
-FIRST_STATLIB:=edev.lib
-FIXED_EXPORT:=?CreatePhysicalDevice@@YAPAVDPhysicalDevice@@XZ
-SUPPORTS_IMPORT_LIBRARY:=0
-SYSTEM_TARGET:=1
-UID2_DEFAULT:=100039d0
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32pdd.flm called with wrong TARGETTYPE (should be 'pdd' but is '$(TARGETTYPE)'))
-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:
+# WINSCW PDD Function Like Makefile (FLM)
+# Build an emulator PDD
+# 
+#
+
+ifeq ($(TARGETTYPE),pdd)
+
+BASE_TYPE=dll
+CW_STATIC_RUNTIME:=1
+FIRST_STATLIB:=edev.lib
+FIXED_EXPORT:=?CreatePhysicalDevice@@YAPAVDPhysicalDevice@@XZ
+SUPPORTS_IMPORT_LIBRARY:=0
+SYSTEM_TARGET:=1
+UID2_DEFAULT:=100039d0
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32pdd.flm called with wrong TARGETTYPE (should be 'pdd' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32pdl.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32pdl.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,34 +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:
-# WINSCW PDL Function Like Makefile (FLM)
-# Build an emulator PDL
-# 
-#
-
-ifeq ($(TARGETTYPE),pdl)
-
-BASE_TYPE:=dll
-CW_STATIC_RUNTIME:=1
-FIRST_STATLIB:=
-FIXED_EXPORT:=?NewPrinterDeviceL@@YAPAVCPrinterDevice@@XZ
-SUPPORTS_IMPORT_LIBRARY:=0
-SYSTEM_TARGET:=0
-UID2_DEFAULT:=10003b1c
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32pdl.flm called with wrong TARGETTYPE (should be 'pdl' but is '$(TARGETTYPE)'))
-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:
+# WINSCW PDL Function Like Makefile (FLM)
+# Build an emulator PDL
+# 
+#
+
+ifeq ($(TARGETTYPE),pdl)
+
+BASE_TYPE:=dll
+CW_STATIC_RUNTIME:=1
+FIRST_STATLIB:=
+FIXED_EXPORT:=?NewPrinterDeviceL@@YAPAVCPrinterDevice@@XZ
+SUPPORTS_IMPORT_LIBRARY:=0
+SYSTEM_TARGET:=0
+UID2_DEFAULT:=10003b1c
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32pdl.flm called with wrong TARGETTYPE (should be 'pdl' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32plugin.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32plugin.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,34 +1,37 @@
-# 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:
-# WINSCW PLUGIN Function Like Makefile (FLM)
-# Build an emulator PLUGIN
-# 
-#
-
-ifeq ($(TARGETTYPE),plugin)
-
-BASE_TYPE:=dll
-CW_STATIC_RUNTIME:=1
-FIRST_STATLIB:=
-FIXED_EXPORT:=?ImplementationGroupProxy@@YAPBUTImplementationProxy@@AAH@Z
-SUPPORTS_IMPORT_LIBRARY:=0
-SYSTEM_TARGET:=0
-UID2_DEFAULT:=10009D8D
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32plugin.flm called with wrong TARGETTYPE (should be 'plugin' but is '$(TARGETTYPE)'))
-endif
+# 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:
+# WINSCW PLUGIN Function Like Makefile (FLM)
+# Build an emulator PLUGIN
+# 
+#
+
+ifneq ($(filter plugin plugin3,$(TARGETTYPE)),)
+BASE_TYPE:=dll
+CW_STATIC_RUNTIME:=1
+FIRST_STATLIB:=
+FIXED_EXPORT:=?ImplementationGroupProxy@@YAPBUTImplementationProxy@@AAH@Z
+SUPPORTS_IMPORT_LIBRARY:=0
+SYSTEM_TARGET:=0
+
+UID2_DEFAULT:=10009D8D
+ifeq ($(TARGETTYPE),plugin3)
+UID2_DEFAULT:=10009D93
+endif
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32plugin.flm called with wrong TARGETTYPE (should be 'plugin' or 'plugin3' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32resource.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32resource.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,25 +1,25 @@
-# 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:
-# Thin Function Like Makefile (FLM) wrapper to general resource building FLM
-# for win32 builds.
-# 
-#
-
-BINCOPYDIRS:=$(EPOCROOT)/epoc32/release/winscw/udeb $(EPOCROOT)/epoc32/release/winscw/urel
-
-# Main (and mostly generic) resource building FLM
-include $(FLMHOME)/resource.flm
-
-# Reset so there it's impossible for it to influence subsequent calls:
-BINCOPYDIRS:=
+# 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:
+# Thin Function Like Makefile (FLM) wrapper to general resource building FLM
+# for win32 builds.
+# 
+#
+
+BINCOPYDIRS:=$(EPOCROOT)/epoc32/release/winscw/udeb $(EPOCROOT)/epoc32/release/winscw/urel
+
+# Main (and mostly generic) resource building FLM
+include $(FLMHOME)/resource.flm
+
+# Reset so there it's impossible for it to influence subsequent calls:
+BINCOPYDIRS:=
--- a/sbsv2/raptor/lib/flm/win32stddll.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32stddll.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,40 +1,40 @@
-# 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:
-# WINSCW Standard DLL Function Like Makefile (FLM)
-# Build an emulator STDDLL
-# 
-#
-
-ifeq ($(TARGETTYPE),stddll)
-
-BASE_TYPE:=dll
-CFLAGS:=$(subst -inline off,,$(CFLAGS))
-CW_STATIC_RUNTIME:=0
-EXPORT_TYPE:=all
-FIRST_STATLIB:=
-FIXED_EXPORT:=
-LFLAGS:=$(subst -nostdlib,-stdlib,$(LFLAGS))
-LIBRARY:=$(LIBRARY) euser.lib backend.lib
-NAME_LOOKUP:=-sym_name_lkup -export_entrypoint_E32Dll
-OPEN_ENVIRONMENT:=1
-SUPPORTS_IMPORT_LIBRARY:=1
-SYSTEM_TARGET:=0
-UID2_DEFAULT:=20004C45
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32stddll.flm called with wrong TARGETTYPE (should be 'stddll' but is '$(TARGETTYPE)'))
-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:
+# WINSCW Standard DLL Function Like Makefile (FLM)
+# Build an emulator STDDLL
+# 
+#
+
+ifeq ($(TARGETTYPE),stddll)
+
+BASE_TYPE:=dll
+CFLAGS:=$(subst -inline off,,$(CFLAGS))
+CW_STATIC_RUNTIME:=0
+EXPORT_TYPE:=all
+FIRST_STATLIB:=
+FIXED_EXPORT:=
+LFLAGS:=$(subst -nostdlib,-stdlib,$(LFLAGS))
+LIBRARY:=$(LIBRARY) euser.lib backend.lib
+NAME_LOOKUP:=-sym_name_lkup -export_entrypoint_E32Dll
+OPEN_ENVIRONMENT:=1
+SUPPORTS_IMPORT_LIBRARY:=1
+SYSTEM_TARGET:=0
+UID2_DEFAULT:=20004C45
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32stddll.flm called with wrong TARGETTYPE (should be 'stddll' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32stdexe.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32stdexe.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,46 +1,46 @@
-# 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:
-# WINSCW Standard EXE Function Like Makefile (FLM)
-# Build an emulator STDEXE
-# 
-#
-
-ifeq ($(TARGETTYPE),stdexe)
-
-BASE_TYPE:=exe
-CFLAGS:=$(subst -inline off,,$(CFLAGS))
-CW_STATIC_RUNTIME:=0
-EXPORT_TYPE:=all
-FIRST_STATLIB:=
-FIXED_EXPORT:=
-LFLAGS:=$(subst -nostdlib,-stdlib,$(LFLAGS))
-LIBRARY:=$(LIBRARY) euser.lib backend.lib
-  
-ifeq ($(WCHARENTRYPOINT),)
-  LIBRARY:=$(LIBRARY) libcrt0.lib
-else
-  LIBRARY:=$(LIBRARY) libwcrt0.lib
-endif
-  
-OPEN_ENVIRONMENT:=1
-SUPPORTS_IMPORT_LIBRARY:=0
-SYSTEM_TARGET:=0
-UID2_DEFAULT:=20004C45
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32stdexe.flm called with wrong TARGETTYPE (should be 'stdexe' but is '$(TARGETTYPE)'))
-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:
+# WINSCW Standard EXE Function Like Makefile (FLM)
+# Build an emulator STDEXE
+# 
+#
+
+ifeq ($(TARGETTYPE),stdexe)
+
+BASE_TYPE:=exe
+CFLAGS:=$(subst -inline off,,$(CFLAGS))
+CW_STATIC_RUNTIME:=0
+EXPORT_TYPE:=all
+FIRST_STATLIB:=
+FIXED_EXPORT:=
+LFLAGS:=$(subst -nostdlib,-stdlib,$(LFLAGS))
+LIBRARY:=$(LIBRARY) euser.lib backend.lib
+  
+ifeq ($(WCHARENTRYPOINT),)
+  LIBRARY:=$(LIBRARY) libcrt0.lib
+else
+  LIBRARY:=$(LIBRARY) libwcrt0.lib
+endif
+  
+OPEN_ENVIRONMENT:=1
+SUPPORTS_IMPORT_LIBRARY:=0
+SYSTEM_TARGET:=0
+UID2_DEFAULT:=20004C45
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32stdexe.flm called with wrong TARGETTYPE (should be 'stdexe' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32stdlib.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32stdlib.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,35 +1,35 @@
-# 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:
-# win32lib.flm
-# WINSCW Standard Static Library Function Like Makefile (FLM)
-# Build an emulator STDLIB
-# 
-#
-
-ifeq ($(TARGETTYPE),stdlib)
-
-BASE_TYPE:=staticlib
-CW_STATIC_RUNTIME:=0
-FIXED_EXPORT:=
-LFLAGS:=$(subst -nostdlib,-stdlib,$(LFLAGS))
-OPEN_ENVIRONMENT:=1
-
-SUPPORTS_IMPORT_LIBRARY:=0
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32stdlib.flm called with wrong TARGETTYPE (should be 'stdlib' but is '$(TARGETTYPE)'))
-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:
+# win32lib.flm
+# WINSCW Standard Static Library Function Like Makefile (FLM)
+# Build an emulator STDLIB
+# 
+#
+
+ifeq ($(TARGETTYPE),stdlib)
+
+BASE_TYPE:=staticlib
+CW_STATIC_RUNTIME:=0
+FIXED_EXPORT:=
+LFLAGS:=$(subst -nostdlib,-stdlib,$(LFLAGS))
+OPEN_ENVIRONMENT:=1
+
+SUPPORTS_IMPORT_LIBRARY:=0
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32stdlib.flm called with wrong TARGETTYPE (should be 'stdlib' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32textnotifier2.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32textnotifier2.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,35 +1,35 @@
-# 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:
-# WINSCW TEXTNOTIFIER2 Function Like Makefile (FLM)
-# Build an emulator TEXTNOTIFIER2
-# 
-#
-
-ifeq ($(TARGETTYPE),textnotifier2)
-
-BASE_TYPE:=dll
-CW_STATIC_RUNTIME:=1
-FIRST_STATLIB:=
-# Actual export is ?NotifierArray@@YAPAV?$CArrayPtr@VMNotifierBase2@@@@XZ
-FIXED_EXPORT:=?NotifierArray@@YAPAV?\$$$$CArrayPtr@VMNotifierBase2@@@@XZ
-SUPPORTS_IMPORT_LIBRARY:=0
-SYSTEM_TARGET:=0
-UID2_DEFAULT:=101fe38b
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32textnotifier2.flm called with wrong TARGETTYPE (should be 'textnotifier2' but is '$(TARGETTYPE)'))
-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:
+# WINSCW TEXTNOTIFIER2 Function Like Makefile (FLM)
+# Build an emulator TEXTNOTIFIER2
+# 
+#
+
+ifeq ($(TARGETTYPE),textnotifier2)
+
+BASE_TYPE:=dll
+CW_STATIC_RUNTIME:=1
+FIRST_STATLIB:=
+# Actual export is ?NotifierArray@@YAPAV?$CArrayPtr@VMNotifierBase2@@@@XZ
+FIXED_EXPORT:=?NotifierArray@@YAPAV?\$$$$CArrayPtr@VMNotifierBase2@@@@XZ
+SUPPORTS_IMPORT_LIBRARY:=0
+SYSTEM_TARGET:=0
+UID2_DEFAULT:=101fe38b
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32textnotifier2.flm called with wrong TARGETTYPE (should be 'textnotifier2' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32var.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32var.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,33 +1,33 @@
-# 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:
-# WINSCW VAR Function Like Makefile (FLM)
-# Build an emulator VAR
-# 
-#
-
-ifeq ($(TARGETTYPE),var)
-
-BASE_TYPE:=dll
-CW_STATIC_RUNTIME:=1
-FIRST_STATLIB:=evar.lib
-FIXED_EXPORT:=
-SUPPORTS_IMPORT_LIBRARY:=1
-SYSTEM_TARGET:=1
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32var.flm called with wrong TARGETTYPE (should be 'var' but is '$(TARGETTYPE)'))
-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:
+# WINSCW VAR Function Like Makefile (FLM)
+# Build an emulator VAR
+# 
+#
+
+ifeq ($(TARGETTYPE),var)
+
+BASE_TYPE:=dll
+CW_STATIC_RUNTIME:=1
+FIRST_STATLIB:=evar.lib
+FIXED_EXPORT:=
+SUPPORTS_IMPORT_LIBRARY:=1
+SYSTEM_TARGET:=1
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32var.flm called with wrong TARGETTYPE (should be 'var' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/lib/flm/win32var2.flm	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/lib/flm/win32var2.flm	Wed Jun 23 16:56:47 2010 +0800
@@ -1,33 +1,33 @@
-# 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:
-# WINSCW VAR Function Like Makefile (FLM)
-# Build an emulator VAR (version 2)
-# 
-#
-
-ifeq ($(TARGETTYPE),var2)
-
-BASE_TYPE:=dll
-CW_STATIC_RUNTIME:=1
-FIRST_STATLIB:=evar.lib
-FIXED_EXPORT:=
-SUPPORTS_IMPORT_LIBRARY:=1
-SYSTEM_TARGET:=1
-
-# Use the general win32 FLM 
-include $(FLMHOME)/win32.flm
-
-else
-$(error $win32var2.flm called with wrong TARGETTYPE (should be 'var2' but is '$(TARGETTYPE)'))
-endif
+# 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:
+# WINSCW VAR Function Like Makefile (FLM)
+# Build an emulator VAR (version 2)
+# 
+#
+
+ifeq ($(TARGETTYPE),var2)
+
+BASE_TYPE:=dll
+CW_STATIC_RUNTIME:=1
+FIRST_STATLIB:=evar.lib
+FIXED_EXPORT:=
+SUPPORTS_IMPORT_LIBRARY:=1
+SYSTEM_TARGET:=1
+
+# Use the general win32 FLM 
+include $(FLMHOME)/win32.flm
+
+else
+$(error $win32var2.flm called with wrong TARGETTYPE (should be 'var2' but is '$(TARGETTYPE)'))
+endif
--- a/sbsv2/raptor/python/dos2unix.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/dos2unix.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,68 +1,68 @@
-#
-# 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: 
-# dos2unix - python version
-# This module converts file from dos to unix i.e. replaces Dos/Windows EOL (CRLF) with Unix EOL (LF).
-# example usage:
-# dos2unix.py windowsFile.txt
-#
-
-import os
-import re
-import sys
-import stat
-#------------------------------------------------------------------------------
-# Converts string from dos to unix i.e. replaces CRLF with LF as a line terminator (EOL)
-#------------------------------------------------------------------------------
-def convertDos2Unix(inputString):
-    regExp = re.compile("\r\n|\n|\r")
-    return regExp.sub("\n",inputString)
-
-#------------------------------------------------------------------------------
-# Validates input
-#------------------------------------------------------------------------------
-def validateInput(argv):
-    if not(len(argv) > 1):
-       print "Error No parameter given: fileName to convert."
-       sys.exit();
-
-#------------------------------------------------------------------------------
-# Reads input file
-#------------------------------------------------------------------------------
-def readInputFile(fileName):
-    inputFile = open(fileName, 'r')
-    # read file content
-    originalFileContent = inputFile.read()
-    inputFile.close()
-    return originalFileContent
-
-#------------------------------------------------------------------------------
-# Writes string to given file (in binary mode)
-#------------------------------------------------------------------------------
-def writeToBinaryFile(string,fileName):
-    os.chmod(fileName, stat.S_IRWXU)
-    outputFile = open(fileName, 'wb')
-    outputFile.write(string)
-    outputFile.close()
-
-# Main script
-
-#------------------------------------------------------------------------------
-# Coverts dos/windows EOL to UNIX EOL (CRLF->LF) in given file
-#------------------------------------------------------------------------------
-def dos2unix(fileName):
-    originalFileContent = readInputFile(fileName)
-    convertedFileContent = convertDos2Unix(originalFileContent)
-    writeToBinaryFile(convertedFileContent,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: 
+# dos2unix - python version
+# This module converts file from dos to unix i.e. replaces Dos/Windows EOL (CRLF) with Unix EOL (LF).
+# example usage:
+# dos2unix.py windowsFile.txt
+#
+
+import os
+import re
+import sys
+import stat
+#------------------------------------------------------------------------------
+# Converts string from dos to unix i.e. replaces CRLF with LF as a line terminator (EOL)
+#------------------------------------------------------------------------------
+def convertDos2Unix(inputString):
+    regExp = re.compile("\r\n|\n|\r")
+    return regExp.sub("\n",inputString)
+
+#------------------------------------------------------------------------------
+# Validates input
+#------------------------------------------------------------------------------
+def validateInput(argv):
+    if not(len(argv) > 1):
+       print "Error No parameter given: fileName to convert."
+       sys.exit();
+
+#------------------------------------------------------------------------------
+# Reads input file
+#------------------------------------------------------------------------------
+def readInputFile(fileName):
+    inputFile = open(fileName, 'r')
+    # read file content
+    originalFileContent = inputFile.read()
+    inputFile.close()
+    return originalFileContent
+
+#------------------------------------------------------------------------------
+# Writes string to given file (in binary mode)
+#------------------------------------------------------------------------------
+def writeToBinaryFile(string,fileName):
+    os.chmod(fileName, stat.S_IRWXU)
+    outputFile = open(fileName, 'wb')
+    outputFile.write(string)
+    outputFile.close()
+
+# Main script
+
+#------------------------------------------------------------------------------
+# Coverts dos/windows EOL to UNIX EOL (CRLF->LF) in given file
+#------------------------------------------------------------------------------
+def dos2unix(fileName):
+    originalFileContent = readInputFile(fileName)
+    convertedFileContent = convertDos2Unix(originalFileContent)
+    writeToBinaryFile(convertedFileContent,fileName)
+
--- a/sbsv2/raptor/python/filter_interface.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/filter_interface.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,34 +1,120 @@
-#
-# 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: 
-# Base Class for defining filter classes
-# All filter classes that get defined should derive from this base class
-#
-
-class Filter(object):
-	
-	def open(self, raptor):
-		return False
-	
-	def write(self, text):
-		return False
-
-	def summary(self):
-		return False
-	
-	def close(self):
-		return False
-	
-	def formatError(self, message):
-		return "sbs: error: " + message + "\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: 
+# Base Class for defining filter classes
+# All filter classes that get defined should derive from this base class
+#
+
+class Filter(object):
+	
+	def open(self, params):
+		return False
+	
+	def write(self, text):
+		return False
+
+	def summary(self):
+		return False
+	
+	def close(self):
+		return False
+	
+	def formatError(self, message):
+		return "sbs: error: " + message + "\n"
+		
+	def formatWarning(self, message):
+		return "sbs: warning: " + message + "\n"	
+
+import sys
+import xml.sax
+
+class FilterSAX(Filter, xml.sax.handler.ContentHandler, xml.sax.handler.ErrorHandler):
+	"base class for filters using a SAX parser"
+	
+	# define these methods in your subclass
+	
+	def startDocument(self):
+		"called once before any elements are seen"
+		pass
+		
+	def startElement(self, name, attributes):
+		"called on the opening of any element"
+		pass
+	
+	def characters(self, char):
+		"called one or more times with body text from an element"
+		pass
+		
+	def endElement(self, name):
+		"called on the closing of any element"
+		pass
+	
+	def endDocument(self):
+		"called once when all elements are closed"
+		pass
+
+	def error(self, exception):
+		"the parse found an error which is (possibly) recoverable"
+		pass
+		
+	def fatalError(self, exception):
+		"the parser thinks an error occurred which should stop everything"
+		pass
+		
+	def warning(self, exception):
+		"the parser found something to complain about that might not matter"
+		pass
+		
+	# these methods are from the Filter base class
+	
+	def open(self, params):
+		"initialise"
+		
+		self.params = params
+		self.ok = True
+		try:
+			self.parser = xml.sax.make_parser(['xml.sax.expatreader'])
+			self.parser.setContentHandler(self)
+			self.parser.setErrorHandler(self)
+			
+		except Exception, ex:
+			sys.stderr.write(self.formatError(str(ex)))
+			self.ok = False
+		
+		return self.ok
+	
+		
+	def write(self, text):
+		"process some log text"
+		try:
+			self.parser.feed(text)
+		except Exception, ex:
+			sys.stderr.write(self.formatError(str(ex)))
+			self.ok = False
+				
+		return self.ok
+	
+
+	def close(self):
+		"finish off"
+		try:
+			self.parser.close()
+		except Exception, ex:
+			sys.stderr.write(self.formatError(str(ex)))
+			self.ok = False
+			
+		return self.ok
+	
+
+# the end
--- a/sbsv2/raptor/python/filter_list.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/filter_list.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,170 +1,204 @@
-#
-# 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 control array of defined logging filters
-# This class will act as a switch, controlling the list of filters iteratively
-#
-
-import os
-import sys
-import raptor
-import filter_interface
-import pluginbox
-import traceback
-
-class FilterWriteException(Exception):
-	def __init__(self, value):
-		self.parameter = value
-	def __str__(self):
-		return repr(self.parameter)
-
-class BootstrapFilter(filter_interface.Filter):
-	def __init__(self):
-		self.out = sys.stdout
-
-	"""Use this until the CLI has supplied some real filters"""
-	def open(self, raptor_instance):
-		"""Set output to stdout for the various I/O methods to write to."""
-		self.raptor = raptor_instance
-		return True
-		
-	def write(self, text):
-		"""Write errors and warnings to stdout"""
-		
-		if text.startswith("<error>"):
-			start = text.find(">")
-			end = text.rfind("<")
-			self.out.write(str(raptor.name) + ": error: %s\n" \
-					% text[(start + 1):end])
-		elif text.startswith("<warning"):
-			start = text.find(">")
-			end = text.rfind("<")
-			self.out.write(str(raptor.name) + ": warning: %s\n" \
-					% text[(start + 1):end])
-		elif "error" in text or "warning" in text:
-			self.out.write(text)
-		return True
-
-	def summary(self):
-		"""Write Summary"""
-		return False
-	
-	def close(self):
-		"""Nothing to do for stdout"""
-		return True
-
-
-
-class FilterList(filter_interface.Filter):
-
-	def __init__(self):
-		self.out = [BootstrapFilter()]
-		self.filters = []
-		self.pbox = None
-
-	def open(self, raptor_instance, filternames, pbox):
-		"""
-			Call open function on each filter using raptor parameters provided
-			Returns: Boolean: Have the functions succeeded in opening the files?
-		"""
-		# Find all the filter plugins
-		self.pbox = pbox
-		possiblefilters = self.pbox.classesof(filter_interface.Filter)
-		unfound = []
-		self.filters = []
-		for f in filternames:
-			unfound.append(f) # unfound unless we find it
-			for pl in possiblefilters:
-				if pl.__name__.upper() == f.upper():
-					self.filters.append(pl())
-					unfound = unfound[:-1]
-		if unfound != []:
-			raise ValueError("requested filters not found: %s \
-			\nAvailable filters are: %s" % (str(unfound), self.format_output_list(possiblefilters)))
-
-		if self.filters == []:
-			self.out = [BootstrapFilter()]
-		else:
-			self.out=[]
-			for filter in self.filters:
-				if filter.open(raptor_instance):
-					self.out.append(filter)
-				else:
-					sys.stderr.write(str(raptor.name) + \
-							": error: Cannot open filter: %s\n" % str(filter))
-					ok = False
-					
-			if self.out == []:
-				sys.stderr.write(str(raptor.name) + \
-						": warning: All filters failed to open. " + \
-						"Defaulting to 'stdout'\n")
-				self.out = [BootstrapFilter()]
-
-	def write(self, text):
-		"""
-			Iterate through each filter, calling their write function
-		"""
-
-		if text is None:
-			return
-
-		badfilters = []
-		for filter in self.out:
-			try:
-				filter.write(text)
-			except Exception,e:
-				traceback.print_exc(file=sys.stdout)
-				sys.stdout.write("Called from: \n")
-				traceback.print_stack(file=sys.stdout)
-				sys.stdout.write("\n")
-				badfilters.append(filter)
-
-		if len(badfilters) > 0:
-			for f in badfilters:
-				self.out.remove(f) # dump the filter in case it causes repeated exceptions
-				sys.stdout.write("Removed filter %s because it generated an exception\n" % type(f))
-
-			if len(self.out) == 0:
-				sys.stdout.write("Falling back to bootstrap filter\n")
-				self.out = [BootstrapFilter()] # Try to fall back to something in the worst case
-
-	def summary(self):
-		"""
-			Run the summaries of all filters (prior to log end)
-		"""
-		for filter in self.out:
-			filter.summary()
-
-	def close(self):
-		"""
-			Iterate through each filter, calling their close function
-			Returns True if all the filters close properly
-		"""
-		returnVal = True
-		
-		for filter in self.out:
-			if (filter != sys.stdout) and (filter != sys.stderr):
-				returnVal = returnVal and filter.close()
-		
-		return returnVal
-
-	def format_output_list(self, possiblefilters):
-		"""
-			formats available filters
-		"""
-		filters_formatted = ""
-		for pl in possiblefilters:
-			filters_formatted += "\n  " + pl.__name__
-		return filters_formatted
-		
+#
+# Copyright (c) 2008-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: 
+# Class to control array of defined logging filters
+# This class will act as a switch, controlling the list of filters iteratively
+#
+
+import os
+import sys
+import raptor
+import re
+import filter_interface
+import pluginbox
+import traceback
+
+class FilterWriteException(Exception):
+	def __init__(self, value):
+		self.parameter = value
+	def __str__(self):
+		return repr(self.parameter)
+
+class BootstrapFilter(filter_interface.Filter):
+	def __init__(self):
+		self.out = sys.stdout
+
+	"""Use this until the CLI has supplied some real filters"""
+	def open(self, raptor_instance):
+		"""Set output to stdout for the various I/O methods to write to."""
+		self.raptor = raptor_instance
+		return True
+		
+	def write(self, text):
+		"""Write errors and warnings to stdout"""
+		
+		if text.startswith("<error>"):
+			start = text.find(">")
+			end = text.rfind("<")
+			self.out.write(str(raptor.name) + ": error: %s\n" \
+					% text[(start + 1):end])
+		elif text.startswith("<warning"):
+			start = text.find(">")
+			end = text.rfind("<")
+			self.out.write(str(raptor.name) + ": warning: %s\n" \
+					% text[(start + 1):end])
+		elif "error" in text or "warning" in text:
+			self.out.write(text)
+		return True
+
+	def summary(self):
+		"""Write Summary"""
+		return False
+	
+	def close(self):
+		"""Nothing to do for stdout"""
+		return True
+
+def SplitList(listString):
+	"""turn a CLI filter string into a list of (class, param) pairs.
+	
+	for example, "foo[a,b],bar[c,d]"
+	
+	becomes [ ("foo", ["a","b"]) , ("bar", ["c","d"]) ]
+	"""
+	matches = re.findall("(\w+)(\[([^\[\]]*)\])?,?", listString)
+	
+	pairs = []
+	for m in matches:
+		classname = m[0]
+		if len(m[2]) > 0:
+			pairs.append( (classname, m[2].split(",")) )
+		else:
+			pairs.append( (classname, []) )
+	return pairs
+	
+class FilterList(filter_interface.Filter):
+
+	def __init__(self):
+		self.out = [BootstrapFilter()]
+		self.filters = []
+		self.pbox = None
+
+	def open(self, raptor_instance, filternames, pbox):
+		"""
+			Call open function on each filter using raptor parameters provided
+			Returns: Boolean: Have the functions succeeded in opening the files?
+		"""
+		# Find all the filter plugins
+		self.pbox = pbox
+		possiblefilters = self.pbox.classesof(filter_interface.Filter)
+		filterdict = {}
+		for p in possiblefilters:
+			name = p.__name__.lower()
+			if name in filterdict:
+				raise ValueError("filters found in SBS_HOME/python/plugins which have duplicate name: %s " % p.__name__)
+			else:
+				filterdict[name] = p
+		
+		# turn "filternames" into a list of (classname, parameters) pairs
+		filterCalls = SplitList(filternames)
+		
+		# look for each filter class in the box
+		unfound = []
+		self.filters = []
+		for (f, params) in filterCalls:
+			# if the filter exists and is a valid filter use it
+			if f.lower() in filterdict:
+				if params:
+					self.filters.append(filterdict[f.lower()](params))
+				else:
+					self.filters.append(filterdict[f.lower()]())
+			else:
+				# record missing filters
+				unfound.append(f)
+
+		if unfound != []:
+			raise ValueError("requested filters not found: %s \
+			\nAvailable filters are: %s" % (str(unfound), self.format_output_list(possiblefilters)))
+
+		if self.filters == []:
+			self.out = [BootstrapFilter()]
+		else:
+			self.out=[]
+			for filter in self.filters:
+				if filter.open(raptor_instance):
+					self.out.append(filter)
+				else:
+					sys.stderr.write(str(raptor.name) + \
+							": error: Cannot open filter: %s\n" % str(filter))
+					ok = False
+					
+			if self.out == []:
+				sys.stderr.write(str(raptor.name) + \
+						": warning: All filters failed to open. " + \
+						"Defaulting to 'stdout'\n")
+				self.out = [BootstrapFilter()]
+
+	def write(self, text):
+		"""
+			Iterate through each filter, calling their write function
+		"""
+
+		if text is None:
+			return
+
+		badfilters = []
+		for filter in self.out:
+			try:
+				filter.write(text)
+			except Exception,e:
+				traceback.print_exc(file=sys.stdout)
+				sys.stdout.write("Called from: \n")
+				traceback.print_stack(file=sys.stdout)
+				sys.stdout.write("\n")
+				badfilters.append(filter)
+
+		if len(badfilters) > 0:
+			for f in badfilters:
+				self.out.remove(f) # dump the filter in case it causes repeated exceptions
+				sys.stdout.write("Removed filter %s because it generated an exception\n" % type(f))
+
+			if len(self.out) == 0:
+				sys.stdout.write("Falling back to bootstrap filter\n")
+				self.out = [BootstrapFilter()] # Try to fall back to something in the worst case
+
+	def summary(self):
+		"""
+			Run the summaries of all filters (prior to log end)
+		"""
+		for filter in self.out:
+			filter.summary()
+
+	def close(self):
+		"""
+			Iterate through each filter, calling their close function
+			Returns True if all the filters close properly
+		"""
+		returnVal = True
+		
+		for filter in self.out:
+			if (filter != sys.stdout) and (filter != sys.stderr):
+				returnVal = returnVal and filter.close()
+		
+		return returnVal
+
+	def format_output_list(self, possiblefilters):
+		"""
+			formats available filters
+		"""
+		filters_formatted = ""
+		for pl in possiblefilters:
+			filters_formatted += "\n  " + pl.__name__
+		return filters_formatted
+		
--- a/sbsv2/raptor/python/filter_utils.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/filter_utils.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,249 +1,254 @@
-#
-# 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: 
-# Classes, methods and regex available for use in log filters
-#
-
-
-import re
-
-
-# General log structure
-logTag = re.compile('</?(?P<name>\?xml|buildlog|info|warning|error|recipe|whatlog|build|export|archive|member|bitmap|resource|stringtable|bmconvcmdfile)[>| ]')
-logHeader = re.compile('<buildlog sbs_version=[\'|\"](?P<version>.+)[\'|\"] xmlns=[\'|\"](?P<xmlns>.+)[\'|\"] xmlns:xsi=[\'|\"](?P<xsdi>.+)[\'|\"] xsi:schemaLocation=[\'|\"](?P<schemaLocation>.+)[\'|\"]>')
-clean = re.compile('.*<rm(dir)? (files|dirs)=[\'|\"](?P<removals>.+)[\'|\"] />')
-exports = re.compile('<info>(Copied|Unzipped (?P<unpacked>\d+) files from) (?P<source>.+) to (?P<destination>.+)</info>')
-
-# Tool errors and warnings
-mwError = re.compile('(.+:\d+:(?! (note|warning):) .+|mw(ld|cc)sym2(.exe)?:(?! (note|warning):) .+ \'.+\' .+)')
-mwWarning = re.compile('.+:\d+: warning: .+|mw(ld|cc)sym2(.exe)?: warning: .+')
-
-
-class AutoFlushedStream(file):
-	""" Wrapper for STDOUT/STDERR streams to ensure that a flush is performed
-	after write methods.
-	Use to avoid buffering when log output in real time is required."""
-	
-	def __init__(self, aStream):
-		self.__stream = aStream
-    
-	def write(self, aText):
-		self.__stream.write(aText)
-		self.__stream.flush()
-
-	def writelines(self, aTextList):
-		self.__stream.writelines(aTextList)
-		self.__stream.flush()
-
-
-class RecipeFactory(object):
-	"Factory class to ease creation of appropriately specialised Recipe objects."
-	
-	def newRecipe(self, aLine=None, aCustomIgnore=None):
-		""" Creates objects of base type Recipe depending on the name
-		of the recipe being processed."""
-		
-		name = ""
-		header = None
-		if aLine:
-			header = Recipe.header.match(aLine)
-		if header:
-			name = header.group("name")	
-		
-		if name.startswith("win32"):
-			return Win32Recipe(aLine, aCustomIgnore)
-		else:
-			return Recipe(aLine, aCustomIgnore)
-	
-
-class Recipe(object):
-	""" Recipe base class.
-	Provides a means to get hold of recipe content in a generic way.
-	Includes a basic understanding of errors and warnings - sub-classes can
-	override output, error and warning methods to specialise."""
-	
-	# Flags to normalise client access, mapping directly to regex groups
-	name		= "name"
-	target		= "target"
-	host		= "host"
-	layer		= "layer"
-	component	= "component"
-	bldinf		= "bldinf"
-	mmp			= "mmp"
-	config		= "config"
-	platform	= "platform"
-	phase		= "phase"
-	source		= "source"
-	start		= "start"
-	elapsed		= "elapsed"
-	exit		= "exit"
-	code		= "code"
-	attempts	= "attempts"
-	
-	# Basic errors/warnings
-	error = re.compile('Error: ')
-	warning = re.compile('Warning: ')
-	
-	# Recipe metadata
-	header  = re.compile('<recipe\s+name=[\'|\"](?P<name>.+)[\'|\"]\s+target=[\'|\"](?P<target>.+)[\'|\"]\s+host=[\'|\"](?P<host>.+)[\'|\"]\s+layer=[\'|\"](?P<layer>.*)[\'|\"]\s+component=[\'|\"](?P<component>.*)[\'|\"]\s+bldinf=[\'|\"](?P<bldinf>.+)[\'|\"]\s+mmp=[\'|\"](?P<mmp>.*)[\'|\"]\s+config=[\'|\"](?P<config>.+)[\'|\"]\s+platform=[\'|\"](?P<platform>.*)[\'|\"]\s+phase=[\'|\"](?P<phase>.+)[\'|\"]\s+source=[\'|\"](?P<source>.*)[\'|\"]\s*>')
-	call    = re.compile('^\+ (?P<call>.+)$')
-	status  = re.compile('\<status\s+exit=[\'|\"](?P<exit>(ok|failed|retry))[\'|\"](\s+code=[\'|\"](?P<code>\d+)[\'|\"])?\s+attempt=[\'|\"](?P<attempts>\d+)[\'|\"]\s*\/>')
-	ignore  = re.compile('<!\[CDATA\[')
-	time    = re.compile(']]><time\s+start=[\'|\"](?P<start>\d+\.\d+)[\'|\"]\s+elapsed=[\'|\"](?P<elapsed>\d+.\d+)[\'|\"]\s*/>$')
-	footer  = re.compile('</recipe>$')
-	
-	
-	def __init__(self, aLine=None, aCustomIgnore=None):
-		"""
-		@param aLine			Optional first line of a recipe (typically the recipe header)
-		@param aCustomIgnore	Optional compiled regular expression object listing additional
-								lines to be ignored in this recipe's output.
-		"""				
-		self.__customIgnore = aCustomIgnore	
-		
-		self.__detail = {
-						Recipe.name		:"",
-						Recipe.target	:"",
-						Recipe.host		:"",
-						Recipe.layer	:"",
-						Recipe.component:"",
-						Recipe.bldinf	:"",
-						Recipe.mmp		:"",
-						Recipe.config	:"",
-						Recipe.platform	:"",
-						Recipe.phase	:"",
-						Recipe.source	:"",
-						Recipe.start	:"",
-						Recipe.elapsed	:0.0,
-						Recipe.exit		:"",
-						Recipe.code		:0,
-						Recipe.attempts	:0
-						}
-		
-		self.__calls = []
-		self.__lines = []
-		self.__complete = False
-		
-		if aLine:
-			self.addLine(aLine)
-	
-	def isComplete(self):
-		"""Signifies that the recipe footer has been reached, the
-		recipe is complete and so is in a fit state to be queried."""
-		return self.__complete
-
-	def __storeDetail(self, aMatchObject):
-		for key in aMatchObject.groupdict().keys():
-			value = aMatchObject.group(key)
-			if value:
-				if (key in [Recipe.code,Recipe.attempts]):
-					value = int(value)
-				elif key == Recipe.elapsed:
-					value = float(value)
-				self.__detail[key] = value
-	
-	def addLine(self, aLine):
-		"""Add a log line to an existing recipe object, processing anything
-		that can be examined at this point in time directly."""
-		if Recipe.ignore.match(aLine) or (self.__customIgnore and self.__customIgnore.match(aLine)):
-			return
-
-		header = Recipe.header.match(aLine)
-		if header:
-			self.__storeDetail(header)
-			return
-		
-		call = Recipe.call.match(aLine)
-		if call:
-			self.__calls.append(call.group("call"))
-			return
-		
-		time = Recipe.time.match(aLine)
-		if time:
-			self.__storeDetail(time)
-			return
-		
-		status = Recipe.status.match(aLine)
-		if status:
-			self.__storeDetail(status)
-			return
-		
-		if Recipe.footer.match(aLine):
-			self.__complete = True
-			return
-
-		self.__lines.append(aLine)
-	
-	def getDetail(self, aItem):
-		"""Retrieve attribute detail from recipe tags.
-		Class data flags provide known items e.g. getDetail(Recipe.source)"""
-		if self.__detail.has_key(aItem):
-			return self.__detail[aItem]
-		
-	def getCalls(self):
-		"Return a list of all '+' prefixed tool calls from this recipe."
-		return self.__calls
-	
-	def isError(self, aLine):
-		"""Convenience matcher for basic errors.
-		Override in sub-classes to specialise."""
-		return True if Recipe.error.match(aLine) else False
-	
-	def isWarning(self, aLine):
-		"""Convenience matcher for basic warnings.
-		Override in sub-classes to specialise."""
-		return True if Recipe.warning.match(aLine) else False
-	
-	def getOutput(self):
-		""""Return a list of all output that isn't an error or a warning.
-		Override in sub-classes to specialise."""
-		output = []
-		for line in self.__lines:
-			if not self.isError(line) and not self.isWarning(line):
-				output.append(line)
-		return output
-	
-	def getErrors(self):
-		""""Return a list of all output identified as an error.
-		Override in sub-classes to specialise."""
-		errors = []
-		for line in self.__lines:
-			if self.isError(line):
-				errors.append(line)
-		return errors
-	
-	def getWarnings(self):
-		""""Return a list of all output identified as a warning.
-		Override in sub-classes to specialise."""
-		warnings = []
-		for line in self.__lines:
-			if self.isWarning(line):
-				warnings.append(line)
-		return warnings
-	
-	def isSuccess(self):
-		"Convenience method to get overall recipe status."
-		return True if self.getDetail(Recipe.exit) == "ok" else False
-	
-	
-class Win32Recipe(Recipe):
-	"Win32 tailored recipe class."
-	def isError(self, aLine):
-		return True if mwError.match(aLine) else False
-	
-	def isWarning(self, aLine):
-		return True if mwWarning.match(aLine) else False
-
-
-	
+#
+# 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: 
+# Classes, methods and regex available for use in log filters
+#
+
+
+import re
+
+
+# General log structure
+logTag = re.compile('</?(?P<name>\?xml|buildlog|info|warning|error|recipe|whatlog|build|export|archive|member|bitmap|resource|stringtable|bmconvcmdfile)[>| ]')
+logHeader = re.compile('<buildlog sbs_version=[\'|\"](?P<version>.+)[\'|\"] xmlns=[\'|\"](?P<xmlns>.+)[\'|\"] xmlns:xsi=[\'|\"](?P<xsdi>.+)[\'|\"] xsi:schemaLocation=[\'|\"](?P<schemaLocation>.+)[\'|\"]>')
+clean = re.compile('.*<rm(dir)? (files|dirs)=[\'|\"](?P<removals>.+)[\'|\"] />')
+exports = re.compile('<info>(Copied|Unzipped (?P<unpacked>\d+) files from) (?P<source>.+) to (?P<destination>.+)</info>')
+
+# Tool errors and warnings
+mwError = re.compile('(.+:\d+:(?! (note|warning):) .+|mw(ld|cc)sym2(.exe)?:(?! (note|warning):) .+ \'.+\' .+)')
+mwWarning = re.compile('.+:\d+: warning: .+|mw(ld|cc)sym2(.exe)?: warning: .+')
+
+
+class AutoFlushedStream(file):
+	""" Wrapper for STDOUT/STDERR streams to ensure that a flush is performed
+	after write methods.
+	Use to avoid buffering when log output in real time is required."""
+	
+	def __init__(self, aStream):
+		self.__stream = aStream
+    
+	def write(self, aText):
+		self.__stream.write(aText)
+		self.__stream.flush()
+
+	def writelines(self, aTextList):
+		self.__stream.writelines(aTextList)
+		self.__stream.flush()
+
+
+class RecipeFactory(object):
+	"Factory class to ease creation of appropriately specialised Recipe objects."
+	
+	def newRecipe(self, aLine=None, aCustomIgnore=None):
+		""" Creates objects of base type Recipe depending on the name
+		of the recipe being processed."""
+		
+		name = ""
+		header = None
+		if aLine:
+			header = Recipe.header.match(aLine)
+		if header:
+			name = header.group("name")	
+		
+		if name.startswith("win32"):
+			return Win32Recipe(aLine, aCustomIgnore)
+		else:
+			return Recipe(aLine, aCustomIgnore)
+	
+
+class Recipe(object):
+	""" Recipe base class.
+	Provides a means to get hold of recipe content in a generic way.
+	Includes a basic understanding of errors and warnings - sub-classes can
+	override output, error and warning methods to specialise."""
+	
+	# Flags to normalise client access, mapping directly to regex groups
+	name		= "name"
+	target		= "target"
+	host		= "host"
+	layer		= "layer"
+	component	= "component"
+	bldinf		= "bldinf"
+	mmp			= "mmp"
+	config		= "config"
+	platform	= "platform"
+	phase		= "phase"
+	source		= "source"
+	start		= "start"
+	elapsed		= "elapsed"
+	exit		= "exit"
+	code		= "code"
+	attempts	= "attempts"
+	
+	# Basic errors/warnings
+	error = re.compile('Error: ')
+	warning = re.compile('Warning: ')
+	
+	# Recipe metadata
+	header  = re.compile('<recipe\s+name=[\'|\"](?P<name>.+)[\'|\"]\s+target=[\'|\"](?P<target>.+)[\'|\"]\s+host=[\'|\"](?P<host>.+)[\'|\"]\s+layer=[\'|\"](?P<layer>.*)[\'|\"]\s+component=[\'|\"](?P<component>.*)[\'|\"]\s+bldinf=[\'|\"](?P<bldinf>.+)[\'|\"]\s+mmp=[\'|\"](?P<mmp>.*)[\'|\"]\s+config=[\'|\"](?P<config>.+)[\'|\"]\s+platform=[\'|\"](?P<platform>.*)[\'|\"]\s+phase=[\'|\"](?P<phase>.+)[\'|\"]\s+source=[\'|\"](?P<source>.*)[\'|\"]\s*>')
+	call    = re.compile('^\+ (?P<call>.+)$')
+	status  = re.compile('\<status\s+exit=[\'|\"](?P<exit>(ok|failed|retry))[\'|\"](\s+code=[\'|\"](?P<code>\d+)[\'|\"])?\s+attempt=[\'|\"](?P<attempts>\d+)[\'|\"]\s*\/>')
+	ignore  = re.compile('<!\[CDATA\[')
+	time    = re.compile(']]><time\s+start=[\'|\"](?P<start>\d+\.\d+)[\'|\"]\s+elapsed=[\'|\"](?P<elapsed>\d+.\d+)[\'|\"]\s*/>$')
+	footer  = re.compile('</recipe>$')
+	
+	
+	def __init__(self, aLine=None, aCustomIgnore=None):
+		"""
+		@param aLine			Optional first line of a recipe (typically the recipe header)
+		@param aCustomIgnore	Optional compiled regular expression object listing additional
+								lines to be ignored in this recipe's output.
+		"""				
+		self.__customIgnore = aCustomIgnore	
+		
+		self.__detail = {
+						Recipe.name		:"",
+						Recipe.target	:"",
+						Recipe.host		:"",
+						Recipe.layer	:"",
+						Recipe.component:"",
+						Recipe.bldinf	:"",
+						Recipe.mmp		:"",
+						Recipe.config	:"",
+						Recipe.platform	:"",
+						Recipe.phase	:"",
+						Recipe.source	:"",
+						Recipe.start	:"",
+						Recipe.elapsed	:0.0,
+						Recipe.exit		:"",
+						Recipe.code		:0,
+						Recipe.attempts	:0
+						}
+		
+		self.__calls = []
+		self.__lines = []
+		self.__complete = False
+		
+		if aLine:
+			self.addLine(aLine)
+	
+	def isComplete(self):
+		"""Signifies that the recipe footer has been reached, the
+		recipe is complete and so is in a fit state to be queried."""
+		return self.__complete
+
+	def __storeDetail(self, aMatchObject):
+		for key in aMatchObject.groupdict().keys():
+			value = aMatchObject.group(key)
+			if value:
+				if (key in [Recipe.code,Recipe.attempts]):
+					value = int(value)
+				elif key == Recipe.elapsed:
+					value = float(value)
+				self.__detail[key] = value
+	
+	def addLine(self, aLine):
+		"""Add a log line to an existing recipe object, processing anything
+		that can be examined at this point in time directly."""
+		if Recipe.ignore.match(aLine) or (self.__customIgnore and self.__customIgnore.match(aLine)):
+			return
+
+		header = Recipe.header.match(aLine)
+		if header:
+			self.__storeDetail(header)
+			return
+		
+		call = Recipe.call.match(aLine)
+		if call:
+			self.__calls.append(call.group("call"))
+			return
+		
+		time = Recipe.time.match(aLine)
+		if time:
+			self.__storeDetail(time)
+			return
+		
+		status = Recipe.status.match(aLine)
+		if status:
+			self.__storeDetail(status)
+			return
+		
+		if Recipe.footer.match(aLine):
+			self.__complete = True
+			return
+
+		self.__lines.append(aLine)
+	
+	def getDetail(self, aItem):
+		"""Retrieve attribute detail from recipe tags.
+		Class data flags provide known items e.g. getDetail(Recipe.source)"""
+		if self.__detail.has_key(aItem):
+			return self.__detail[aItem]
+		
+	def getCalls(self):
+		"Return a list of all '+' prefixed tool calls from this recipe."
+		return self.__calls
+	
+	def isError(self, aLine):
+		"""Convenience matcher for basic errors.
+		Override in sub-classes to specialise."""
+		if Recipe.error.match(aLine):
+			return True
+		return False
+	
+	def isWarning(self, aLine):
+		"""Convenience matcher for basic warnings.
+		Override in sub-classes to specialise."""
+		if Recipe.warning.match(aLine):
+			return True
+		return False
+	
+	def getOutput(self):
+		""""Return a list of all output that isn't an error or a warning.
+		Override in sub-classes to specialise."""
+		output = []
+		for line in self.__lines:
+			if not self.isError(line) and not self.isWarning(line):
+				output.append(line)
+		return output
+	
+	def getErrors(self):
+		""""Return a list of all output identified as an error.
+		Override in sub-classes to specialise."""
+		errors = []
+		for line in self.__lines:
+			if self.isError(line):
+				errors.append(line)
+		return errors
+	
+	def getWarnings(self):
+		""""Return a list of all output identified as a warning.
+		Override in sub-classes to specialise."""
+		warnings = []
+		for line in self.__lines:
+			if self.isWarning(line):
+				warnings.append(line)
+		return warnings
+	
+	def isSuccess(self):
+		"Convenience method to get overall recipe status."
+		return (self.getDetail(Recipe.exit) == "ok")
+	
+	
+class Win32Recipe(Recipe):
+	"Win32 tailored recipe class."
+	def isError(self, aLine):
+		if mwError.match(aLine):
+			return True
+		return False
+	
+	def isWarning(self, aLine):
+		if mwWarning.match(aLine):
+			return True
+		return False
--- a/sbsv2/raptor/python/generic_path.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/generic_path.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,315 +1,346 @@
-#
-# 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: 
-# generic_path module
-#
-
-import os
-import sys
-import re
-import types
-
-# are we on windows, and if so what is the current drive letter
-isWin = sys.platform.lower().startswith("win")
-if isWin:
-	drive = re.match('^([A-Za-z]:)',os.getcwd()).group(0)
-
-# regex for "bare" drive letters	
-driveRE = re.compile('^[A-Za-z]:$')
-
-# Base class
-
-class Path:
-	"""This class represents a file path.
-	
-	A generic path object supports operations without needing to know
-	about Windows and Linux differences. The standard str() function can
-	obtain a string version of the path in Local format for use by
-	platform-specific functions (file opening for example).
-	
-	We use forward slashes as path separators (even on Windows).
-	
-	For example,
-	
-		path1 = generic_path.Path("/foo")
-		path2 = generic_path.Path("bar", "bing.bang")
-		
-		print str(path1.Append(path2))
-		
-	Prints /foo/bar/bing.bang		on Linux
-	Prints c:/foo/bar/bing.bang		on Windows (if c is the current drive)
-	""" 
-		
-	def __init__(self, *arguments):
-		"""construct a path from a list of path elements"""
-		
-		if len(arguments) == 0:
-			self.path = ""
-			return
-		
-		list = []
-		for i,arg in enumerate(arguments):
-			if isWin:
-				if i == 0:
-					# If the first element starts with \ or / then we will
-					# add the current drive letter to make a fully absolute path
-					if arg.startswith("\\\\"):
-						list.append(arg) # A UNC path - don't mess with it
-					elif arg.startswith("\\") or arg.startswith("/"):
-						list.append(drive + arg)
-					# If the first element is a bare drive then dress it with a \
-					# temporarily otherwise "join" will not work properly.
-					elif driveRE.match(arg):
-						list.append(arg + "\\")
-					# nothing special about the first element
-					else:
-						list.append(arg)
-				else:
-					if arg.startswith("\\\\"):
-						raise ValueError("non-initial path components must not start with \\\\ : %s" % arg)
-					else:
-						list.append(arg)
-				if ";" in arg:
-					raise ValueError("An individual windows Path may not contain ';' : %s" % arg)
-			else:
-				list.append(arg)
-	
-		self.path = os.path.join(*list)
-		
-		# normalise to avoid nastiness with dots and multiple separators
-		# but do not normalise "" as it will become "."
-		if self.path != "":
-			self.path = os.path.normpath(self.path)
-		
-		# always use forward slashes as separators
-		self.path = self.path.replace("\\", "/")
-		
-		# remove trailing slashes unless we are just /
-		if self.path != "/":
-			self.path = self.path.rstrip("/")
-		
-	def __str__(self):
-		return self.path
-	
-	def GetNeutralStr(self):
-		"""return the path as a string that could be included in other paths."""
-		return self.path.replace(":","").replace("/","")
-
-	def GetLocalString(self):
-		"""return a string in the local file-system format.
-		
-		e.g. C:/tmp on Windows or /C/tmp on Linux"""
-		return self.path
-	
-	def isAbsolute(self):
-		"test whether this path is absolute or relative"
-		# C: is an absolute directory
-		return (os.path.isabs(self.path) or driveRE.match(self.path))
-	
-	def Absolute(self):
-		"""return an object for the absolute version of this path.
-		
-		Prepends the current working directory to relative paths and
-		the current drive (on Windows) to /something type paths."""
-		# leave C: alone as abspath will stick the cwd on
-		if driveRE.match(self.path):
-			return Path(self.path)
-		else:
-			return Path(os.path.abspath(self.path))
-	
-	def Append(self, *arguments):
-		"return an object with path elements added at the end of this path"
-		return Join(*((self,) + arguments))
-	
-	def Prepend(self, *arguments):
-		"return an object with path elements added at the start of this path"
-		return Join(*(arguments + (self,)))
-	
-	def isDir(self):
-		"test whether this path points to an existing directory"
-		# C: is a directory
-		return (os.path.isdir(self.path) or driveRE.match(self.path))
-	
-	def isFile(self):
-		"test whether this path points to an existing file"
-		return os.path.isfile(self.path)
-
-	def Exists(self):
-		"test whether this path exists in the filesystem"
-		if driveRE.match(self.path):
-			return os.path.exists(self.path + "/")
-		else:
-			return os.path.exists(self.path)
-		
-	def Dir(self):
-		"return an object for the directory part of this path"
-		if driveRE.match(self.path):
-			return Path(self.path)
-		else:
-			return Path(os.path.dirname(self.path))
-
-	def File(self):
-		"return a string for the file part of this path"
-		return os.path.basename(self.path)
-
-	def Components(self):
-		"""return a list of the components of this path."""
-		return self.path.split('/')
-
-	def FindCaseless(self):
-		"""Given a path which may not be not correct in terms of case,
-		search the filesystem to find the corresponding, correct path.
-		paths are assumed to be absolute and normalised (which they
-		should be in this class).
-
-		Assumes that the path is more right than wrong, i.e. starts
-		with the full path and tests for existence - then takes the
-		last component off and check for that.
-
-		This will be inefficient if used in cases where the file 
-		has a high probability of not existing.
-		"""
-
-		if os.path.exists(self.path):
-			return Path(self.path)
-
-		unknown_elements = []
-		tail = self.path
-		head = None
-		while tail != '': 
-			if os.path.exists(tail):
-				break
-			else:
-				(tail,head) = os.path.split(tail)
-				#print "(head,tail) = (%s,%s)\n" % (head,tail)
-				unknown_elements.append(head)
-
-		if tail == None:
-			result = ""
-		else:
-			result = tail
-
-		# Now we know the bits that may be wrong so we can search for them
-		unknown_elements.reverse()
-		for item in unknown_elements:
-			possible = os.path.join(result, item) 
-			if os.path.exists(possible):
-				result = possible
-				continue # not finished yet - only this element is ok
-
-			# Nope, we really do have to search for this component of the path
-			possible = None
-			if result:
-				for file in os.listdir(result):
-					if file.lower() == item.lower():
-						possible = os.path.join(result,file)
-						break # find first matching name (might not be right)
-				if possible is None:
-					result = "" 
-					break # really couldn't find the file
-				result = possible
-
-		if result == "":
-			return None
-
-		return Path(result)
-
-	def From(self,source):
-		"""Returns the relative path from 'source' to here."""
-		list1 = source.Absolute().Components()
-		list2 = self.Absolute().Components()
-
-		# on windows if the drives are different
-		# then the relative path is the absolute one.
-		if isWin and list1[0] != list2[0]:
-			return self.Absolute()
-
-		final_list = []
-		for item in list1:
-			if list2 != []:
-				for widget in list2:
-					if item == widget:
-						list2.pop(0)
-						break
-					else:
-						final_list.insert(0, "..")
-						final_list.append(widget)
-						list2.pop(0)
-						break
-			else:
-				final_list.insert(0, "..")
-
-		final_list.extend(list2)
-
-		return Join(*final_list)
-
-	def GetShellPath(self):
-		"""Returns correct slashes according to os type as a string
-		"""
-		if isWin:
-			if  "OSTYPE" in os.environ and os.environ['OSTYPE'] == "cygwin" :
-				return self.path
-
-			return self.path.replace("/", "\\")
-
-		return self.path
-
-
-# Module functions
-
-def Join(*arguments):
-	"""Concatenate the given list to make a generic path object. 
-	
-	This can accept both strings and Path objects, and join
-	them "intelligently" to make a complete path."""
-	list = []
-	for arg in arguments:
-		if isinstance(arg, Path):
-			list.append(arg.path)
-		else:
-			list.append(arg)
-		
-	return Path(*list)
-
-def CurrentDir():
-	"return a Path object for the current working directory"
-	return Path(os.getcwd())
-
-def NormalisePathList(aList):
-	"""Convert a list of strings into a list of Path objects"""
-	return map(lambda x: Path(x), aList)
-
-def Where(afile):
-	"""Return the location of a file 'afile' in the system path.
-	
-	On windows, adds .exe onto the filename if it's not there. Returns the first location it found or None if it wasn't found.
-	
-	>>> Where("python")
-	"/usr/bin/python"
-	>>> Where("nonexistentfile")
-	None
-	"""
-	location = None
-	if sys.platform.startswith("win"):
-		if not afile.lower().endswith(".exe"):
-			afile += ".exe"
-			
-	for current_file in [os.path.join(loop_number,afile) for loop_number in
-			     os.environ["PATH"].split(os.path.pathsep)]:
-		if os.path.isfile(current_file):
-			location = current_file
-			break
-	return location
-
-# end of generic_path module
+#
+# 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: 
+# generic_path module
+#
+
+import os
+import sys
+import re
+import types
+import ctypes
+
+# are we on windows, and if so what is the current drive letter
+isWin = sys.platform.lower().startswith("win")
+if isWin:
+	drive = re.match('^([A-Za-z]:)',os.getcwd()).group(0)
+
+# regex for "bare" drive letters	
+driveRE = re.compile('^[A-Za-z]:$')
+
+# Base class
+
+class Path:
+	"""This class represents a file path.
+	
+	A generic path object supports operations without needing to know
+	about Windows and Linux differences. The standard str() function can
+	obtain a string version of the path in Local format for use by
+	platform-specific functions (file opening for example).
+	
+	We use forward slashes as path separators (even on Windows).
+	
+	For example,
+	
+		path1 = generic_path.Path("/foo")
+		path2 = generic_path.Path("bar", "bing.bang")
+		
+		print str(path1.Append(path2))
+		
+	Prints /foo/bar/bing.bang		on Linux
+	Prints c:/foo/bar/bing.bang		on Windows (if c is the current drive)
+	""" 
+		
+	def __init__(self, *arguments):
+		"""construct a path from a list of path elements"""
+		
+		if len(arguments) == 0:
+			self.path = ""
+			return
+		
+		list = []
+		for i,arg in enumerate(arguments):
+			if isWin:
+				if i == 0:
+					# If the first element starts with \ or / then we will
+					# add the current drive letter to make a fully absolute path
+					if arg.startswith("\\\\"):
+						list.append(arg) # A UNC path - don't mess with it
+					elif arg.startswith("\\") or arg.startswith("/"):
+						list.append(drive + arg)
+					# If the first element is a bare drive then dress it with a \
+					# temporarily otherwise "join" will not work properly.
+					elif driveRE.match(arg):
+						list.append(arg + "\\")
+					# nothing special about the first element
+					else:
+						list.append(arg)
+				else:
+					if arg.startswith("\\\\"):
+						raise ValueError("non-initial path components must not start with \\\\ : %s" % arg)
+					else:
+						list.append(arg)
+				if ";" in arg:
+					raise ValueError("An individual windows Path may not contain ';' : %s" % arg)
+			else:
+				list.append(arg)
+	
+		self.path = os.path.join(*list)
+		
+		# normalise to avoid nastiness with dots and multiple separators
+		# but do not normalise "" as it will become "."
+		if self.path != "":
+			self.path = os.path.normpath(self.path)
+		
+		# always use forward slashes as separators
+		self.path = self.path.replace("\\", "/")
+		
+		# remove trailing slashes unless we are just /
+		if self.path != "/":
+			self.path = self.path.rstrip("/")
+		
+	def __str__(self):
+		return self.path
+	
+	def GetNeutralStr(self):
+		"""return the path as a string that could be included in other paths."""
+		return self.path.replace(":","").replace("/","")
+
+	def GetLocalString(self):
+		"""return a string in the local file-system format.
+		
+		e.g. C:/tmp on Windows or /C/tmp on Linux"""
+		return self.path
+	
+	def isAbsolute(self):
+		"test whether this path is absolute or relative"
+		# C: is an absolute directory
+		return (os.path.isabs(self.path) or driveRE.match(self.path))
+	
+	def Absolute(self):
+		"""return an object for the absolute version of this path.
+		
+		Prepends the current working directory to relative paths and
+		the current drive (on Windows) to /something type paths."""
+		# leave C: alone as abspath will stick the cwd on
+		if driveRE.match(self.path):
+			return Path(self.path)
+		else:
+			return Path(os.path.abspath(self.path))
+	
+	def Append(self, *arguments):
+		"return an object with path elements added at the end of this path"
+		return Join(*((self,) + arguments))
+	
+	def Prepend(self, *arguments):
+		"return an object with path elements added at the start of this path"
+		return Join(*(arguments + (self,)))
+	
+	def isDir(self):
+		"test whether this path points to an existing directory"
+		# C: is a directory
+		return (os.path.isdir(self.path) or driveRE.match(self.path))
+	
+	def isFile(self):
+		"test whether this path points to an existing file"
+		return os.path.isfile(self.path)
+
+	def Exists(self):
+		"test whether this path exists in the filesystem"
+		if driveRE.match(self.path):
+			return os.path.exists(self.path + "/")
+		else:
+			return os.path.exists(self.path)
+		
+	def Dir(self):
+		"return an object for the directory part of this path"
+		if driveRE.match(self.path):
+			return Path(self.path)
+		else:
+			return Path(os.path.dirname(self.path))
+
+	def File(self):
+		"return a string for the file part of this path"
+		return os.path.basename(self.path)
+
+	def Components(self):
+		"""return a list of the components of this path."""
+		return self.path.split('/')
+
+	def FindCaseless(self):
+		"""Given a path which may not be not correct in terms of case,
+		search the filesystem to find the corresponding, correct path.
+		paths are assumed to be absolute and normalised (which they
+		should be in this class).
+
+		Assumes that the path is more right than wrong, i.e. starts
+		with the full path and tests for existence - then takes the
+		last component off and check for that.
+
+		This will be inefficient if used in cases where the file 
+		has a high probability of not existing.
+		"""
+
+		if os.path.exists(self.path):
+			return Path(self.path)
+
+		unknown_elements = []
+		tail = self.path
+		head = None
+		while tail != '': 
+			if os.path.exists(tail):
+				break
+			else:
+				(tail,head) = os.path.split(tail)
+				#print "(head,tail) = (%s,%s)\n" % (head,tail)
+				unknown_elements.append(head)
+
+		if tail == None:
+			result = ""
+		else:
+			result = tail
+
+		# Now we know the bits that may be wrong so we can search for them
+		unknown_elements.reverse()
+		for item in unknown_elements:
+			possible = os.path.join(result, item) 
+			if os.path.exists(possible):
+				result = possible
+				continue # not finished yet - only this element is ok
+
+			# Nope, we really do have to search for this component of the path
+			possible = None
+			if result:
+				for file in os.listdir(result):
+					if file.lower() == item.lower():
+						possible = os.path.join(result,file)
+						break # find first matching name (might not be right)
+				if possible is None:
+					result = "" 
+					break # really couldn't find the file
+				result = possible
+
+		if result == "":
+			return None
+
+		return Path(result)
+
+	def From(self,source):
+		"""Returns the relative path from 'source' to here."""
+		list1 = source.Absolute().Components()
+		list2 = self.Absolute().Components()
+
+		# on windows if the drives are different
+		# then the relative path is the absolute one.
+		if isWin and list1[0] != list2[0]:
+			return self.Absolute()
+
+		final_list = []
+		for item in list1:
+			if list2 != []:
+				for widget in list2:
+					if item == widget:
+						list2.pop(0)
+						break
+					else:
+						final_list.insert(0, "..")
+						final_list.append(widget)
+						list2.pop(0)
+						break
+			else:
+				final_list.insert(0, "..")
+
+		final_list.extend(list2)
+
+		return Join(*final_list)
+
+	def GetShellPath(self):
+		"""Returns correct slashes according to os type as a string
+		"""
+		if isWin:
+			if  "OSTYPE" in os.environ and os.environ['OSTYPE'] == "cygwin" :
+				return self.path
+
+			return self.path.replace("/", "\\")
+
+		return self.path
+
+	def GetSpaceSafePath(self):
+		"""Returns a version of the path where spaces don't interfere with shell interpretation.
+		
+		This functionality only applies to Windows - paths containing spaces are assumed to be problematic
+		on non-Windows platforms.
+		
+		On Windows, the path is returned in Windows-specific 8.3 short path form - tilde are used to replace
+		spaces and fit path elements within 8.3 requirements.  As 8.3 format paths are not guaranteed to be
+		supported on all Windows installs, and can only be calculated if they exist, a newly formated path is
+		only returned if it is returned by the Windows API and tested to exist.
+		"""
+		
+		if not isWin:
+			return None
+		
+		from ctypes.wintypes import DWORD, LPSTR, MAX_PATH
+
+		GetShortPathNameA = ctypes.windll.kernel32.GetShortPathNameA
+		GetShortPathNameA.restype = DWORD
+		GetShortPathNameA.argtypes = LPSTR, LPSTR, DWORD
+		
+		buffer = ctypes.create_string_buffer(MAX_PATH)
+		GetShortPathNameA(self.path, buffer, MAX_PATH)
+		
+		spacesafe = buffer.value
+		
+		if not spacesafe or not os.path.exists(spacesafe):
+			return None
+		
+		return spacesafe
+		
+# Module functions
+
+def Join(*arguments):
+	"""Concatenate the given list to make a generic path object. 
+	
+	This can accept both strings and Path objects, and join
+	them "intelligently" to make a complete path."""
+	list = []
+	for arg in arguments:
+		if isinstance(arg, Path):
+			list.append(arg.path)
+		else:
+			list.append(arg)
+		
+	return Path(*list)
+
+def CurrentDir():
+	"return a Path object for the current working directory"
+	return Path(os.getcwd())
+
+def NormalisePathList(aList):
+	"""Convert a list of strings into a list of Path objects"""
+	return map(lambda x: Path(x), aList)
+
+def Where(afile):
+	"""Return the location of a file 'afile' in the system path.
+	
+	On windows, adds .exe onto the filename if it's not there. Returns the first location it found or None if it wasn't found.
+	
+	>>> Where("python")
+	"/usr/bin/python"
+	>>> Where("nonexistentfile")
+	None
+	"""
+	location = None
+	if sys.platform.startswith("win"):
+		if not afile.lower().endswith(".exe"):
+			afile += ".exe"
+			
+	for current_file in [os.path.join(loop_number,afile) for loop_number in
+			     os.environ["PATH"].split(os.path.pathsep)]:
+		if os.path.isfile(current_file):
+			location = current_file
+			break
+	return location
+
+# end of generic_path module
--- a/sbsv2/raptor/python/mmpparser.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/mmpparser.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,388 +1,390 @@
-#
-# 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: 
-# MMPParser module
-# This module provides a parser for MMP files which can work
-# with any supplied MMPBackend
-#
-
-
-# We have to define the grammar in the following order:
-# Actions - because the rules reference them
-# Terminals - because the rules use them
-# Rules
-# Root rule - e.g. "an MMP is a list of statements"
-#
-# This seems inverted but it's just the price of
-# being able to use python to define the grammar.
-
-
-from pyparsing import *
-import sys
-
-# For multiline matching we must exclude \n from the list of whitespace
-# characters.  If we don't then Parse Elements like OneOrMore won't stop
-# at line boundaries.
-# \r doesn't matter as it is always followed by \n anyhow it is
-# redundant and may be thrown away without any loss of information.
-ParserElement.setDefaultWhitespaceChars('\t\r ')
-
-
-
-
-## Useful Parse Elements #########################################
-def String():
-	return Regex('[^ \n]+')
-
-def StringList():
-	return Group(OneOrMore(Regex('[^ \n]+')))
-
-def HexOrDecNumber():
-	return Regex('(0[xX][0-9a-fA-Z]+)|([0-9]+)')
-
-def Line(pattern):
-	return pattern.copy() + LineEnd().suppress()
-
-
-
-class MMPParser(object):
-	# Tools for whom options may be specified
-	tools = [ 'ARMCC', 'CW', 'GCC', 'MSVC', 'GCCXML', 'ARMASM', 'GCCE' ]
-
-
-	def __init__(self,statemachine):
-		self.backend = statemachine
-		# Create Tokens for the tools we support
-		self.toolName = CaselessKeyword(MMPParser.tools[0])
-		for thisTool in MMPParser.tools[1:]:
-			self.toolName ^= CaselessKeyword(thisTool)
-
-		self.assignment = \
-			( \
-			Line(CaselessKeyword('ARMFPU') + String()) ^ \
-			Line(CaselessKeyword('ASSPLIBRARY') + StringList()) ^ \
-			Line(CaselessKeyword('CAPABILITY') + StringList()) ^ \
-			Line(CaselessKeyword('DOCUMENT') + StringList()) ^ \
-			Line(CaselessKeyword('EPOCHEAPSIZE') + HexOrDecNumber() + HexOrDecNumber()) ^ \
-			Line(CaselessKeyword('EPOCPROCESSPRIORITY') + String()) ^ \
-			Line(CaselessKeyword('FIRSTLIB') + String()) ^ \
-			Line(CaselessKeyword('TARGET') + String()) ^ \
-			Line(CaselessKeyword('ROMTARGET') + Optional(StringList())) ^ \
-			Line(CaselessKeyword('RAMTARGET') + String()) ^ \
-			Line(CaselessKeyword('TARGETTYPE') + String()) ^ \
-			Line(CaselessKeyword('TARGETPATH') + String()) ^ \
-			Line(CaselessKeyword('SYSTEMINCLUDE') + StringList()) ^ \
-			Line(CaselessKeyword('USERINCLUDE') + StringList()) ^ \
-			Line(CaselessKeyword('DEFFILE') + String()) ^ \
-			Line(CaselessKeyword('EXPORTLIBRARY') + String()) ^ \
-			Line(CaselessKeyword('LINKAS') + String()) ^ \
-			Line(CaselessKeyword('VENDORID') + HexOrDecNumber()) ^ \
-			Line(CaselessKeyword('OPTION') + self.toolName + StringList()) ^ \
-			Line(CaselessKeyword('LINKEROPTION') + self.toolName + StringList()) ^\
-			Line(CaselessKeyword('OPTION_REPLACE') + self.toolName + StringList()) ^ \
-			Line(CaselessKeyword('SECUREID') + HexOrDecNumber()) ^ \
-			Line(CaselessKeyword('EPOCSTACKSIZE') + HexOrDecNumber()) ^ \
-			Line(CaselessKeyword('VERSION') + String() + Optional(CaselessKeyword('EXPLICIT'))) ^ \
-			Line(CaselessKeyword('EPOCPROCESSPRIORITY') + String()) ^ \
-			Line(CaselessKeyword('NEWLIB') + String()) \
-			).setParseAction(self.backend.doAssignment) ^ \
-			( \
-			Line(CaselessKeyword('SOURCE') + StringList()).setParseAction(self.backend.doSourceAssignment) \
-			).setParseAction(self.backend.doSourceAssignment) ^ \
-			( \
-			Line(CaselessKeyword('RESOURCE') + StringList()).setParseAction(self.backend.doOldResourceAssignment) \
-			).setParseAction(self.backend.doOldResourceAssignment) ^ \
-			( \
-			Line(CaselessKeyword('SYSTEMRESOURCE') + StringList()).setParseAction(self.backend.doResourceAssignment) \
-			).setParseAction(self.backend.doOldResourceAssignment) ^ \
-			( \
-			Line(CaselessKeyword('SOURCEPATH') + String()).setParseAction(self.backend.doSourceAssignment) \
-			).setParseAction(self.backend.doSourcePathAssignment) ^ \
-			( \
-			Line((CaselessKeyword('UID') + Group(HexOrDecNumber() + Optional(HexOrDecNumber())))).setParseAction(self.backend.doUIDAssignment) \
-			).setParseAction(self.backend.doUIDAssignment)  ^ \
-			( \
-			Line(CaselessKeyword('LANG') + StringList()) \
-			).setParseAction(self.backend.doAppend) ^ \
-			( \
-			Line(CaselessKeyword('LIBRARY') + StringList()) \
-			).setParseAction(self.backend.doAppend) ^ \
-			( \
-			Line(CaselessKeyword('DEBUGLIBRARY') + StringList()) \
-			).setParseAction(self.backend.doAppend) ^ \
-			( \
-			Line(CaselessKeyword('MACRO') + Optional(StringList())) \
-			).setParseAction(self.backend.doAppend) ^ \
-			( \
-			Line(CaselessKeyword('AIF') + StringList()) \
-			).setParseAction(self.backend.doDeprecated) ^ \
-			( \
-			Line(CaselessKeyword('STATICLIBRARY') + StringList()) \
-			).setParseAction(self.backend.doAppend)
-
-		self.switch = \
-			(Line( \
-			CaselessKeyword('ALWAYS_BUILD_AS_ARM') ^ \
-			CaselessKeyword('ASSPEXPORTS') ^ \
-			CaselessKeyword('ASSPABI') ^ \
-			CaselessKeyword('ASSPEXPORTS') ^ \
-			CaselessKeyword('DEBUGGABLE') ^ \
-			CaselessKeyword('DEBUGGABLE_UDEBONLY') ^ \
-			CaselessKeyword('EPOCALLOWDLLDATA') ^ \
-			CaselessKeyword('EPOCCALLDLLENTRYPOINTS') ^ \
-			CaselessKeyword('EPOCFIXEDPROCESS') ^ \
-			CaselessKeyword('EXPORTUNFROZEN') ^ \
-			CaselessKeyword('FEATUREVARIANT') ^ \
-			CaselessKeyword('BYTEPAIRCOMPRESSTARGET') ^ \
-			CaselessKeyword('INFLATECOMPRESSTARGET') ^ \
-			CaselessKeyword('NOCOMPRESSTARGET') ^ \
-			CaselessKeyword('NOLINKTIMECODEGENERATION') ^ \
-			CaselessKeyword('NOMULTIFILECOMPILATION') ^ \
-			CaselessKeyword('COMPRESSTARGET') ^ \
-			CaselessKeyword('NOEXPORTLIBRARY') ^ \
-			CaselessKeyword('NOSTRICTDEF') ^ \
-			CaselessKeyword('SRCDBG') ^ \
-			CaselessKeyword('STRICTDEPEND') ^ \
-			CaselessKeyword('STDCPP') ^ \
-			CaselessKeyword('NOSTDCPP') ^ \
-			CaselessKeyword('SMPSAFE') ^ \
-			CaselessKeyword('PAGED') ^ \
-			CaselessKeyword('PAGEDCODE') ^ \
-			CaselessKeyword('PAGEDDATA') ^ \
-			CaselessKeyword('UNPAGED') ^ \
-			CaselessKeyword('UNPAGEDCODE') ^ \
-			CaselessKeyword('UNPAGEDDATA') ^ \
-			CaselessKeyword('WCHARENTRYPOINT') \
-			)).setParseAction(self.backend.doSetSwitch)
-
-		# General
-
-		self.blankline = (LineStart() + Regex('[\t\r ]*') + LineEnd().suppress() \
-			).setParseAction(self.backend.doBlankLine)
-
-		self.preProcessorComment = (LineStart() + Regex('# .*') + LineEnd().suppress() 
-			).setParseAction(self.backend.doPreProcessorComment)
-
-		self.unknownstatement = (LineStart() + Regex('.*\S+') + LineEnd().suppress() \
-			).setParseAction(self.backend.doUnknownStatement)
-			
-		self.unknownBlockBody = (\
-			(Regex("[^\n]+?\s*") + LineEnd().suppress()).setParseAction(self.backend.doStartUnknown) + \
-			ZeroOrMore(self.unknownstatement) \
-			).setParseAction(self.backend.doEndUnknown) 
-
-		# Platform
-
-		self.ARMCCBlockStatement = \
-			self.blankline ^ self.preProcessorComment ^ \
-			Line( \
-			CaselessKeyword('ARMRT') ^ \
-			CaselessKeyword('ARMINC') \
-			).setParseAction(self.backend.doSetSwitch) ^ \
-			Line( \
-			(CaselessKeyword('ARMLIBS') + StringList()) \
-			).setParseAction(self.backend.doAppend)
-
-		self.WINSBlockStatement = \
-			self.blankline ^ self.preProcessorComment ^ \
-			Line( \
-			(CaselessKeyword('BASEADDRESS') + HexOrDecNumber()) \
-			).setParseAction(self.backend.doAssignment) ^ \
-			Line( \
-			(CaselessKeyword('WIN32_LIBRARY') + StringList()) \
-			).setParseAction(self.backend.doAppend) ^ \
-			Line( \
-			(CaselessKeyword('WIN32_RESOURCE') + StringList()) \
-			).setParseAction(self.backend.doAppend) ^ \
-			Line( \
-			CaselessKeyword('WIN32_HEADERS') ^ \
-			CaselessKeyword('COPY_FOR_STATIC_LINKAGE')			
-			).setParseAction(self.backend.doSetSwitch)
-
-		self.TOOLSBlockStatement = \
-			self.blankline ^ self.preProcessorComment ^ \
-			Line( \
-			(CaselessKeyword('WIN32_LIBRARY') + StringList()) \
-			).setParseAction(self.backend.doAppend)
-
-		self.platformBlock = ( \
-			((CaselessKeyword('ARMCC') + LineEnd().suppress()).setParseAction(self.backend.doStartPlatform) + ZeroOrMore(self.ARMCCBlockStatement)) ^ \
-			((CaselessKeyword('WINS') + LineEnd().suppress()).setParseAction(self.backend.doStartPlatform) + ZeroOrMore(self.WINSBlockStatement)) ^ \
-			((CaselessKeyword('WINSCW') + LineEnd().suppress()).setParseAction(self.backend.doStartPlatform) + ZeroOrMore(self.WINSBlockStatement)) ^ \
-			(CaselessKeyword('MARM') + LineEnd().suppress()).setParseAction(self.backend.doStartPlatform) ^ \
-			((CaselessKeyword('TOOLS') + LineEnd().suppress()).setParseAction(self.backend.doStartPlatform) + ZeroOrMore(self.TOOLSBlockStatement)) ^ \
-			(CaselessKeyword('WINC') + LineEnd().suppress()).setParseAction(self.backend.doStartPlatform) + ZeroOrMore(self.WINSBlockStatement) \
-			).setParseAction(self.backend.doEndPlatform)
-
-		# Resource
-			
-		self.resourceSetting= \
-			self.blankline ^ self.preProcessorComment ^ \
-			Line( \
-			(CaselessKeyword('TARGET') + String()) ^ \
-			(CaselessKeyword('TARGETPATH') + String()) ^ \
-			(CaselessKeyword('UID') + HexOrDecNumber()) \
-			).setParseAction(self.backend.doResourceAssignment) ^ \
-			Line( \
-			(CaselessKeyword('DEPENDS') + StringList()) ^ \
-			(CaselessKeyword('LANG') + StringList()) \
-			).setParseAction(self.backend.doResourceAppend) ^ \
-			Line( \
-			CaselessKeyword('HEADER') ^ \
-			CaselessKeyword('HEADERONLY')
-			).setParseAction(self.backend.doResourceSetSwitch)
-
-		self.resourceBlockBody = (\
-			(CaselessKeyword('RESOURCE') + String() + LineEnd().suppress()).setParseAction(self.backend.doStartResource) \
-			 + ZeroOrMore(self.resourceSetting) \
-			).setParseAction(self.backend.doEndResource)
-
-		# Bitmap
-
-		self.bitmapSetting = \
-			self.blankline ^ self.preProcessorComment ^ \
-			Line( \
-			(CaselessKeyword('TARGETPATH') + String()) \
-			).setParseAction(self.backend.doBitmapAssignment) ^\
-			Line( \
-			(CaselessKeyword('SOURCE') + StringList()) 
-			).setParseAction(self.backend.doBitmapSourceAssignment) ^\
-			Line( \
-			(CaselessKeyword('SOURCEPATH') + String()) 
-			).setParseAction(self.backend.doBitmapSourcePathAssignment) ^\
-			Line( \
-			CaselessKeyword('HEADER')
-			).setParseAction(self.backend.doBitmapSetSwitch)
-			
-		self.bitmapBlockBody = (\
-			(CaselessKeyword('BITMAP') + String() + LineEnd().suppress()).setParseAction(self.backend.doStartBitmap) + \
-			ZeroOrMore(self.bitmapSetting) \
-			).setParseAction(self.backend.doEndBitmap)
-			
-		# Stringtable
-		
-		self.stringTableSetting = \
-			self.blankline ^ self.preProcessorComment ^ \
-			Line( \
-			(CaselessKeyword('EXPORTPATH') + String())		
-			).setParseAction(self.backend.doStringTableAssignment) ^\
-			Line( \
-			CaselessKeyword('HEADERONLY') \
-			).setParseAction(self.backend.doStringTableSetSwitch)
-			
-		self.stringTableBlockBody = (\
-			(CaselessKeyword('STRINGTABLE') + String() + LineEnd().suppress()).setParseAction(self.backend.doStartStringTable) + \
-			ZeroOrMore(self.stringTableSetting) \
-			).setParseAction(self.backend.doEndStringTable)		
-
-		# Top-level
-		self.block = \
-			LineStart() + CaselessLiteral("START") + White().suppress() + \
-			(self.platformBlock ^ self.resourceBlockBody ^ self.bitmapBlockBody ^ self.stringTableBlockBody ^self.unknownBlockBody) +  \
-			LineStart() + CaselessLiteral("END") + LineEnd().suppress()
-					
-
-		self.command = \
-			 self.assignment ^ self.switch
-	
-		# Unknown blocks and statements are ordered i.e. if there's a failure to match something before,
-		# then they're "caught" appropriately
-		
-		self.mmp = (ZeroOrMore(self.preProcessorComment ^ self.blankline ^ self.block ^ self.command ^ self.unknownstatement)).setParseAction(self.backend.doMMP) 
-
-
-## MMP Parsing Backends #########################################
-class MMPBackend(object):
-	"""A "backend" for the MMP language
-	This may be used to implement a build system,
-	source analysis tool or anything else"""
-	def __init__(self):
-		super(MMPBackend,self).__init__()
-	def doPreProcessorComment(self,s,loc,toks):
-		return "OK"
-	
-	def doStartPlatform(self,s,loc,toks):
-		return "OK"
-	def doEndPlatform(self,s,loc,toks):
-		return "OK"
-
-	def doStartResource(self,s,loc,toks):
-		return "OK"
-	def doResourceAssignment(self,s,loc,toks):
-		return "OK"
-	def doResourceAppend(self,s,loc,toks):
-		return "OK"
-	def doResourceSetSwitch(self,s,loc,toks):
-		return "OK"	
-	def doEndResource(self,s,loc,toks):
-		return "OK"
-
-	def doStartBitmap(self,s,loc,toks):
-		return "OK" 
-	def doBitmapAssignment(self,s,loc,toks):
-		return "OK" 
-	def doBitmapSourceAssignment(self,s,loc,toks):
-		return "OK" 
-	def doBitmapSourcePathAssignment(self,s,loc,toks):
-		return "OK" 
-	def doBitmapSetSwitch(self,s,loc,toks):
-		return "OK" 
-	def doEndBitmap(self,s,loc,toks):
-		return "OK"
-
-	def doStartStringtable(self,s,loc,toks):
-		return "OK" 
-	def doStringTableAssignment(self,s,loc,toks):
-		return "OK" 
-	def doStringTableSetSwitch(self,s,loc,toks):
-		return "OK" 	
-	def doEndStringtable(self,s,loc,toks):
-		return "OK"
-
-	def doSetSwitch(self,s,loc,toks):
-		return "OK"
-	def doAppend(self,s,loc,toks):
-		return "OK"
-	def doAssignment(self,s,loc,toks):
-		return "OK"
-	def doUIDAssignment(self,s,loc,toks):
-		return "OK"
-	def doSourcePathAssignment(self,s,loc,toks):
-		return "OK"
-	def doSourceAssignment(self,s,loc,toks):
-		return "OK"
-	
-	def doOldResourceAssignment(self,s,loc,toks):
-		return "OK"
-	
-	def doUnknownStatement(self,s,loc,toks):
-		return "OK"
-	def doStartUnknown(self,s,loc,toks):
-		return "OK"
-	def doEndUnknown(self,s,loc,toks):
-		return "OK"
-	
-	def doBlankLine(self,s,loc,toks):
-		return "OK"
-	
-	def doDeprecated(self,s,loc,toks):
-		return "OK"
-		
-	def doNothing(self):
-		return "OK"
-	
-	def doMMP(self,s,loc,toks):
-		return "MMP"
-
-
+#
+# 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: 
+# MMPParser module
+# This module provides a parser for MMP files which can work
+# with any supplied MMPBackend
+#
+
+
+# We have to define the grammar in the following order:
+# Actions - because the rules reference them
+# Terminals - because the rules use them
+# Rules
+# Root rule - e.g. "an MMP is a list of statements"
+#
+# This seems inverted but it's just the price of
+# being able to use python to define the grammar.
+
+
+from pyparsing import *
+import sys
+
+# For multiline matching we must exclude \n from the list of whitespace
+# characters.  If we don't then Parse Elements like OneOrMore won't stop
+# at line boundaries.
+# \r doesn't matter as it is always followed by \n anyhow it is
+# redundant and may be thrown away without any loss of information.
+ParserElement.setDefaultWhitespaceChars('\t\r ')
+
+
+
+
+## Useful Parse Elements #########################################
+def String():
+	return Regex('[^ \n]+')
+
+def StringList():
+	return Group(OneOrMore(Regex('[^ \n]+')))
+
+def HexOrDecNumber():
+	return Regex('(0[xX][0-9a-fA-Z]+)|([0-9]+)')
+
+def Line(pattern):
+	return pattern.copy() + LineEnd().suppress()
+
+
+
+class MMPParser(object):
+	# Tools for whom options may be specified
+	tools = [ 'ARMCC', 'CW', 'GCC', 'MSVC', 'GCCXML', 'ARMASM', 'GCCE' ]
+
+
+	def __init__(self,statemachine):
+		self.backend = statemachine
+		# Create Tokens for the tools we support
+		self.toolName = CaselessKeyword(MMPParser.tools[0])
+		for thisTool in MMPParser.tools[1:]:
+			self.toolName ^= CaselessKeyword(thisTool)
+
+		self.assignment = \
+			( \
+			Line(CaselessKeyword('ARMFPU') + String()) ^ \
+			Line(CaselessKeyword('APPLY') + String()) ^ \
+			Line(CaselessKeyword('ASSPLIBRARY') + StringList()) ^ \
+			Line(CaselessKeyword('CAPABILITY') + StringList()) ^ \
+			Line(CaselessKeyword('DOCUMENT') + StringList()) ^ \
+			Line(CaselessKeyword('EPOCHEAPSIZE') + HexOrDecNumber() + HexOrDecNumber()) ^ \
+			Line(CaselessKeyword('EPOCPROCESSPRIORITY') + String()) ^ \
+			Line(CaselessKeyword('FIRSTLIB') + String()) ^ \
+			Line(CaselessKeyword('TARGET') + String()) ^ \
+			Line(CaselessKeyword('ROMTARGET') + Optional(StringList())) ^ \
+			Line(CaselessKeyword('RAMTARGET') + String()) ^ \
+			Line(CaselessKeyword('TARGETTYPE') + String()) ^ \
+			Line(CaselessKeyword('TARGETPATH') + String()) ^ \
+			Line(CaselessKeyword('SYSTEMINCLUDE') + StringList()) ^ \
+			Line(CaselessKeyword('USERINCLUDE') + StringList()) ^ \
+			Line(CaselessKeyword('DEFFILE') + String()) ^ \
+			Line(CaselessKeyword('EXPORTLIBRARY') + String()) ^ \
+			Line(CaselessKeyword('LINKAS') + String()) ^ \
+			Line(CaselessKeyword('VENDORID') + HexOrDecNumber()) ^ \
+			Line(CaselessKeyword('OPTION') + self.toolName + StringList()) ^ \
+			Line(CaselessKeyword('LINKEROPTION') + self.toolName + StringList()) ^\
+			Line(CaselessKeyword('OPTION_REPLACE') + self.toolName + StringList()) ^ \
+			Line(CaselessKeyword('SECUREID') + HexOrDecNumber()) ^ \
+			Line(CaselessKeyword('EPOCSTACKSIZE') + HexOrDecNumber()) ^ \
+			Line(CaselessKeyword('VERSION') + String() + Optional(CaselessKeyword('EXPLICIT'))) ^ \
+			Line(CaselessKeyword('EPOCPROCESSPRIORITY') + String()) ^ \
+			Line(CaselessKeyword('NEWLIB') + String()) \
+			).setParseAction(self.backend.doAssignment) ^ \
+			( \
+			Line(CaselessKeyword('SOURCE') + StringList()).setParseAction(self.backend.doSourceAssignment) \
+			).setParseAction(self.backend.doSourceAssignment) ^ \
+			( \
+			Line(CaselessKeyword('RESOURCE') + StringList()).setParseAction(self.backend.doOldResourceAssignment) \
+			).setParseAction(self.backend.doOldResourceAssignment) ^ \
+			( \
+			Line(CaselessKeyword('SYSTEMRESOURCE') + StringList()).setParseAction(self.backend.doResourceAssignment) \
+			).setParseAction(self.backend.doOldResourceAssignment) ^ \
+			( \
+			Line(CaselessKeyword('SOURCEPATH') + String()).setParseAction(self.backend.doSourceAssignment) \
+			).setParseAction(self.backend.doSourcePathAssignment) ^ \
+			( \
+			Line((CaselessKeyword('UID') + Group(HexOrDecNumber() + Optional(HexOrDecNumber())))).setParseAction(self.backend.doUIDAssignment) \
+			).setParseAction(self.backend.doUIDAssignment)  ^ \
+			( \
+			Line(CaselessKeyword('LANG') + StringList()) \
+			).setParseAction(self.backend.doAppend) ^ \
+			( \
+			Line(CaselessKeyword('LIBRARY') + StringList()) \
+			).setParseAction(self.backend.doAppend) ^ \
+			( \
+			Line(CaselessKeyword('DEBUGLIBRARY') + StringList()) \
+			).setParseAction(self.backend.doAppend) ^ \
+			( \
+			Line(CaselessKeyword('MACRO') + Optional(StringList())) \
+			).setParseAction(self.backend.doAppend) ^ \
+			( \
+			Line(CaselessKeyword('AIF') + StringList()) \
+			).setParseAction(self.backend.doDeprecated) ^ \
+			( \
+			Line(CaselessKeyword('STATICLIBRARY') + StringList()) \
+			).setParseAction(self.backend.doAppend)
+
+		self.switch = \
+			(Line( \
+			CaselessKeyword('ALWAYS_BUILD_AS_ARM') ^ \
+			CaselessKeyword('ASSPEXPORTS') ^ \
+			CaselessKeyword('ASSPABI') ^ \
+			CaselessKeyword('ASSPEXPORTS') ^ \
+			CaselessKeyword('DEBUGGABLE') ^ \
+			CaselessKeyword('DEBUGGABLE_UDEBONLY') ^ \
+			CaselessKeyword('EPOCALLOWDLLDATA') ^ \
+			CaselessKeyword('EPOCCALLDLLENTRYPOINTS') ^ \
+			CaselessKeyword('EPOCFIXEDPROCESS') ^ \
+			CaselessKeyword('EPOCNESTEDEXCEPTIONS') ^ \
+			CaselessKeyword('EXPORTUNFROZEN') ^ \
+			CaselessKeyword('FEATUREVARIANT') ^ \
+			CaselessKeyword('BYTEPAIRCOMPRESSTARGET') ^ \
+			CaselessKeyword('INFLATECOMPRESSTARGET') ^ \
+			CaselessKeyword('NOCOMPRESSTARGET') ^ \
+			CaselessKeyword('NOLINKTIMECODEGENERATION') ^ \
+			CaselessKeyword('NOMULTIFILECOMPILATION') ^ \
+			CaselessKeyword('COMPRESSTARGET') ^ \
+			CaselessKeyword('NOEXPORTLIBRARY') ^ \
+			CaselessKeyword('NOSTRICTDEF') ^ \
+			CaselessKeyword('SRCDBG') ^ \
+			CaselessKeyword('STRICTDEPEND') ^ \
+			CaselessKeyword('STDCPP') ^ \
+			CaselessKeyword('NOSTDCPP') ^ \
+			CaselessKeyword('SMPSAFE') ^ \
+			CaselessKeyword('PAGED') ^ \
+			CaselessKeyword('PAGEDCODE') ^ \
+			CaselessKeyword('PAGEDDATA') ^ \
+			CaselessKeyword('UNPAGED') ^ \
+			CaselessKeyword('UNPAGEDCODE') ^ \
+			CaselessKeyword('UNPAGEDDATA') ^ \
+			CaselessKeyword('WCHARENTRYPOINT') \
+			)).setParseAction(self.backend.doSetSwitch)
+
+		# General
+
+		self.blankline = (LineStart() + Regex('[\t\r ]*') + LineEnd().suppress() \
+			).setParseAction(self.backend.doBlankLine)
+
+		self.preProcessorComment = (LineStart() + Regex('# .*') + LineEnd().suppress() 
+			).setParseAction(self.backend.doPreProcessorComment)
+
+		self.unknownstatement = (LineStart() + Regex('.*\S+') + LineEnd().suppress() \
+			).setParseAction(self.backend.doUnknownStatement)
+			
+		self.unknownBlockBody = (\
+			(Regex("[^\n]+?\s*") + LineEnd().suppress()).setParseAction(self.backend.doStartUnknown) + \
+			ZeroOrMore(self.unknownstatement) \
+			).setParseAction(self.backend.doEndUnknown) 
+
+		# Platform
+
+		self.ARMCCBlockStatement = \
+			self.blankline ^ self.preProcessorComment ^ \
+			Line( \
+			CaselessKeyword('ARMRT') ^ \
+			CaselessKeyword('ARMINC') \
+			).setParseAction(self.backend.doSetSwitch) ^ \
+			Line( \
+			(CaselessKeyword('ARMLIBS') + StringList()) \
+			).setParseAction(self.backend.doAppend)
+
+		self.WINSBlockStatement = \
+			self.blankline ^ self.preProcessorComment ^ \
+			Line( \
+			(CaselessKeyword('BASEADDRESS') + HexOrDecNumber()) \
+			).setParseAction(self.backend.doAssignment) ^ \
+			Line( \
+			(CaselessKeyword('WIN32_LIBRARY') + StringList()) \
+			).setParseAction(self.backend.doAppend) ^ \
+			Line( \
+			(CaselessKeyword('WIN32_RESOURCE') + StringList()) \
+			).setParseAction(self.backend.doAppend) ^ \
+			Line( \
+			CaselessKeyword('WIN32_HEADERS') ^ \
+			CaselessKeyword('COPY_FOR_STATIC_LINKAGE')			
+			).setParseAction(self.backend.doSetSwitch)
+
+		self.TOOLSBlockStatement = \
+			self.blankline ^ self.preProcessorComment ^ \
+			Line( \
+			(CaselessKeyword('WIN32_LIBRARY') + StringList()) \
+			).setParseAction(self.backend.doAppend)
+
+		self.platformBlock = ( \
+			((CaselessKeyword('ARMCC') + LineEnd().suppress()).setParseAction(self.backend.doStartPlatform) + ZeroOrMore(self.ARMCCBlockStatement)) ^ \
+			((CaselessKeyword('WINS') + LineEnd().suppress()).setParseAction(self.backend.doStartPlatform) + ZeroOrMore(self.WINSBlockStatement)) ^ \
+			((CaselessKeyword('WINSCW') + LineEnd().suppress()).setParseAction(self.backend.doStartPlatform) + ZeroOrMore(self.WINSBlockStatement)) ^ \
+			(CaselessKeyword('MARM') + LineEnd().suppress()).setParseAction(self.backend.doStartPlatform) ^ \
+			((CaselessKeyword('TOOLS') + LineEnd().suppress()).setParseAction(self.backend.doStartPlatform) + ZeroOrMore(self.TOOLSBlockStatement)) ^ \
+			(CaselessKeyword('WINC') + LineEnd().suppress()).setParseAction(self.backend.doStartPlatform) + ZeroOrMore(self.WINSBlockStatement) \
+			).setParseAction(self.backend.doEndPlatform)
+
+		# Resource
+			
+		self.resourceSetting= \
+			self.blankline ^ self.preProcessorComment ^ \
+			Line( \
+			(CaselessKeyword('TARGET') + String()) ^ \
+			(CaselessKeyword('TARGETPATH') + String()) ^ \
+			(CaselessKeyword('UID') + HexOrDecNumber()) \
+			).setParseAction(self.backend.doResourceAssignment) ^ \
+			Line( \
+			(CaselessKeyword('DEPENDS') + StringList()) ^ \
+			(CaselessKeyword('LANG') + StringList()) \
+			).setParseAction(self.backend.doResourceAppend) ^ \
+			Line( \
+			CaselessKeyword('HEADER') ^ \
+			CaselessKeyword('HEADERONLY')
+			).setParseAction(self.backend.doResourceSetSwitch)
+
+		self.resourceBlockBody = (\
+			(CaselessKeyword('RESOURCE') + String() + LineEnd().suppress()).setParseAction(self.backend.doStartResource) \
+			 + ZeroOrMore(self.resourceSetting) \
+			).setParseAction(self.backend.doEndResource)
+
+		# Bitmap
+
+		self.bitmapSetting = \
+			self.blankline ^ self.preProcessorComment ^ \
+			Line( \
+			(CaselessKeyword('TARGETPATH') + String()) \
+			).setParseAction(self.backend.doBitmapAssignment) ^\
+			Line( \
+			(CaselessKeyword('SOURCE') + StringList()) 
+			).setParseAction(self.backend.doBitmapSourceAssignment) ^\
+			Line( \
+			(CaselessKeyword('SOURCEPATH') + String()) 
+			).setParseAction(self.backend.doBitmapSourcePathAssignment) ^\
+			Line( \
+			CaselessKeyword('HEADER')
+			).setParseAction(self.backend.doBitmapSetSwitch)
+			
+		self.bitmapBlockBody = (\
+			(CaselessKeyword('BITMAP') + String() + LineEnd().suppress()).setParseAction(self.backend.doStartBitmap) + \
+			ZeroOrMore(self.bitmapSetting) \
+			).setParseAction(self.backend.doEndBitmap)
+			
+		# Stringtable
+		
+		self.stringTableSetting = \
+			self.blankline ^ self.preProcessorComment ^ \
+			Line( \
+			(CaselessKeyword('EXPORTPATH') + String())		
+			).setParseAction(self.backend.doStringTableAssignment) ^\
+			Line( \
+			CaselessKeyword('HEADERONLY') \
+			).setParseAction(self.backend.doStringTableSetSwitch)
+			
+		self.stringTableBlockBody = (\
+			(CaselessKeyword('STRINGTABLE') + String() + LineEnd().suppress()).setParseAction(self.backend.doStartStringTable) + \
+			ZeroOrMore(self.stringTableSetting) \
+			).setParseAction(self.backend.doEndStringTable)		
+
+		# Top-level
+		self.block = \
+			LineStart() + CaselessLiteral("START") + White().suppress() + \
+			(self.platformBlock ^ self.resourceBlockBody ^ self.bitmapBlockBody ^ self.stringTableBlockBody ^self.unknownBlockBody) +  \
+			LineStart() + CaselessLiteral("END") + LineEnd().suppress()
+					
+
+		self.command = \
+			 self.assignment ^ self.switch
+	
+		# Unknown blocks and statements are ordered i.e. if there's a failure to match something before,
+		# then they're "caught" appropriately
+		
+		self.mmp = (ZeroOrMore(self.preProcessorComment ^ self.blankline ^ self.block ^ self.command ^ self.unknownstatement)).setParseAction(self.backend.doMMP) 
+
+
+## MMP Parsing Backends #########################################
+class MMPBackend(object):
+	"""A "backend" for the MMP language
+	This may be used to implement a build system,
+	source analysis tool or anything else"""
+	def __init__(self):
+		super(MMPBackend,self).__init__()
+	def doPreProcessorComment(self,s,loc,toks):
+		return "OK"
+	
+	def doStartPlatform(self,s,loc,toks):
+		return "OK"
+	def doEndPlatform(self,s,loc,toks):
+		return "OK"
+
+	def doStartResource(self,s,loc,toks):
+		return "OK"
+	def doResourceAssignment(self,s,loc,toks):
+		return "OK"
+	def doResourceAppend(self,s,loc,toks):
+		return "OK"
+	def doResourceSetSwitch(self,s,loc,toks):
+		return "OK"	
+	def doEndResource(self,s,loc,toks):
+		return "OK"
+
+	def doStartBitmap(self,s,loc,toks):
+		return "OK" 
+	def doBitmapAssignment(self,s,loc,toks):
+		return "OK" 
+	def doBitmapSourceAssignment(self,s,loc,toks):
+		return "OK" 
+	def doBitmapSourcePathAssignment(self,s,loc,toks):
+		return "OK" 
+	def doBitmapSetSwitch(self,s,loc,toks):
+		return "OK" 
+	def doEndBitmap(self,s,loc,toks):
+		return "OK"
+
+	def doStartStringtable(self,s,loc,toks):
+		return "OK" 
+	def doStringTableAssignment(self,s,loc,toks):
+		return "OK" 
+	def doStringTableSetSwitch(self,s,loc,toks):
+		return "OK" 	
+	def doEndStringtable(self,s,loc,toks):
+		return "OK"
+
+	def doSetSwitch(self,s,loc,toks):
+		return "OK"
+	def doAppend(self,s,loc,toks):
+		return "OK"
+	def doAssignment(self,s,loc,toks):
+		return "OK"
+	def doUIDAssignment(self,s,loc,toks):
+		return "OK"
+	def doSourcePathAssignment(self,s,loc,toks):
+		return "OK"
+	def doSourceAssignment(self,s,loc,toks):
+		return "OK"
+	
+	def doOldResourceAssignment(self,s,loc,toks):
+		return "OK"
+	
+	def doUnknownStatement(self,s,loc,toks):
+		return "OK"
+	def doStartUnknown(self,s,loc,toks):
+		return "OK"
+	def doEndUnknown(self,s,loc,toks):
+		return "OK"
+	
+	def doBlankLine(self,s,loc,toks):
+		return "OK"
+	
+	def doDeprecated(self,s,loc,toks):
+		return "OK"
+		
+	def doNothing(self):
+		return "OK"
+	
+	def doMMP(self,s,loc,toks):
+		return "MMP"
+
+
--- a/sbsv2/raptor/python/pluginbox.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/pluginbox.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,68 +1,68 @@
-#
-# 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: 
-# PluginBox module - finds classes 
-#
-
-from os import listdir
-import re
-from types import TypeType, ModuleType
-import sys
-
-class PluginModule(object):
-	"""Represents a module containing plugin classes """
-	def __init__(self, file):
-		self.module = __import__(file)
-		self.classes = []
-		self.__findclasses(self.module)
-
-	def __findclasses(self,module):
-		for c in module.__dict__:
-			mbr = module.__dict__[c]
-			if type(mbr) == TypeType:
-				self.classes.append(mbr)
-
-class PluginBox(object):
-	"""
-	A container that locates all the classes in a directory.
-	Example usage:
-
-		from person import Person
-		ps = PluginBox("plugins")
-		people = []
-		for i in ps.classesof(Person):
-			people.append(i())
-
-	"""
-	plugfilenamere=re.compile('^(.*)\.py$',re.I)
-	def __init__(self, plugindirectory):
-		self.pluginlist = []
-		self.plugindir = plugindirectory
-		sys.path.append(str(self.plugindir))
-		for f in listdir(plugindirectory):
-			m = PluginBox.plugfilenamere.match(f)
-			if m is not None:
-				self.pluginlist.append(PluginModule(m.groups()[0]))
-		sys.path = sys.path[:-1]
-
-	def classesof(self, classtype):
-		"""return a list of all classes that are subclasses of <classtype>"""
-		classes = []
-		for p in self.pluginlist:
-			for c in p.classes:
-				if issubclass(c, classtype):
-					if c.__name__ != classtype.__name__:
-						classes.append(c)
-		return classes
-
+#
+# 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: 
+# PluginBox module - finds classes 
+#
+
+from os import listdir
+import re
+from types import TypeType, ModuleType
+import sys
+
+class PluginModule(object):
+	"""Represents a module containing plugin classes """
+	def __init__(self, file):
+		self.module = __import__(file)
+		self.classes = []
+		self.__findclasses(self.module)
+
+	def __findclasses(self,module):
+		for c in module.__dict__:
+			mbr = module.__dict__[c]
+			if type(mbr) == TypeType:
+				self.classes.append(mbr)
+
+class PluginBox(object):
+	"""
+	A container that locates all the classes in a directory.
+	Example usage:
+
+		from person import Person
+		ps = PluginBox("plugins")
+		people = []
+		for i in ps.classesof(Person):
+			people.append(i())
+
+	"""
+	plugfilenamere=re.compile('^(.*)\.py$',re.I)
+	def __init__(self, plugindirectory):
+		self.pluginlist = []
+		self.plugindir = plugindirectory
+		sys.path.append(str(self.plugindir))
+		for f in listdir(plugindirectory):
+			m = PluginBox.plugfilenamere.match(f)
+			if m is not None:
+				self.pluginlist.append(PluginModule(m.groups()[0]))
+		sys.path = sys.path[:-1]
+
+	def classesof(self, classtype):
+		"""return a list of all classes that are subclasses of <classtype>"""
+		classes = []
+		for p in self.pluginlist:
+			for c in p.classes:
+				if issubclass(c, classtype):
+					if c.__name__ != classtype.__name__:
+						classes.append(c)
+		return classes
+
--- a/sbsv2/raptor/python/plugins/dummyplugin.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/plugins/dummyplugin.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,22 +1,22 @@
-#
-# 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: 
-# Test plugin
-#
-
-
-class DummyPlugin(object):
-	def __init__(self):
-		print "DummyPlugin Init"
-
+#
+# 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: 
+# Test plugin
+#
+
+
+class DummyPlugin(object):
+	def __init__(self):
+		print "DummyPlugin Init"
+
--- a/sbsv2/raptor/python/plugins/filter_carbide.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/plugins/filter_carbide.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,133 +1,132 @@
-#
-# 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: 
-# Format Raptor verbose log output for the Carbide IDE
-#
-
-
-import os
-import re
-import sys
-import raptor
-import filter_interface
-import filter_utils
-
-
-class FilterCarbide(filter_interface.Filter):
-	"""Carbide IDE filter
-	Strips most verbose output leaving tools calls, tool output and formatted errors/warnings."""
-	
-	# ignore all general, benign, make output
-	ignore = re.compile('(make(\.exe)?: Nothing to be done for \`.+\'|make(\.exe)?: \[.+\] Error \d+ \(ignored\)|.*make(.exe)?\[\d\]: (Entering|Leaving) directory \`.+\')')
-	
-	stdout = filter_utils.AutoFlushedStream(sys.stdout)
-	stderr = filter_utils.AutoFlushedStream(sys.stderr)
-	
-	recipeFactory = filter_utils.RecipeFactory()
-	
-	def __init__(self):
-		self.__errors = 0
-		self.__warnings = 0
-		self.__recipe = None
-
-	def open(self, aRaptorInstance):
-		return True
-		
-	def write(self, aLine):
-		"""Process output on the fly and format appropriately for the Carbide IDE.
-		Most verbose output is discarded leaving tools calls, tool output and formatted errors
-		and warnings.
-		Identified errors go to stderr so that they will be highlighted in the IDE console."""
-		
-		if FilterCarbide.ignore.match(aLine):
-			return
-		
-		logHeader = filter_utils.logHeader.match(aLine)
-		if logHeader:
-			FilterCarbide.stdout.write("sbs version: " + logHeader.group("version")+"\n\n")
-			return
-		
-		clean = filter_utils.clean.match(aLine)
-		if clean:
-			for file in clean.group("removals").split():
-				FilterCarbide.stdout.write("clean: " + file + "\n")
-			return
-		
-		exports = filter_utils.exports.match(aLine)
-		if exports:
-			FilterCarbide.stdout.write("export: " + exports.group("source") + " to " + exports.group("destination") + "\n")
-			return
-		
-		
-		if self.__recipe:
-			self.__recipe.addLine(aLine)
-			
-			if self.__recipe.isComplete():
-				for call in self.__recipe.getCalls():
-					FilterCarbide.stdout.write(call + "\n")				
-		else:		
-			logTag = filter_utils.logTag.match(aLine)
-			if logTag:
-				tagName = logTag.group("name")			
-				if tagName == "recipe":
-					if self.__recipe:
-						self.__recipe.addLine(aLine)
-					else:
-						self.__recipe = FilterCarbide.recipeFactory.newRecipe(aLine)						
-				elif tagName == "error":
-					self.__errors += 1
-					FilterCarbide.stderr.write("Error: " + filter_utils.logTag.sub("", aLine) + "\n")
-				elif tagName == "warning":
-					self.__warnings += 1
-					FilterCarbide.stdout.write("Warning: " + filter_utils.logTag.sub("", aLine) + "\n")
-				# we're not interested in any other tagged output
-				return
-			else:
-				# Not a recipe, and not tagged output that we know about.
-				# Output this anyway, just in case it's something important
-				FilterCarbide.stdout.write(aLine)
-		
-		
-		if self.__recipe and self.__recipe.isComplete():
-			errors = 0
-			warnings = 0			
-
-			recipeOutput = self.__recipe.getOutput()
-			recipeWarnings = self.__recipe.getWarnings()
-			recipeErrors = self.__recipe.getErrors()
-
-			if len(recipeOutput):
-				FilterCarbide.stdout.writelines(recipeOutput)		
-			if len(recipeWarnings):
-				FilterCarbide.stdout.writelines(recipeWarnings)
-				warnings += len(recipeWarnings)
-			if len(recipeErrors):
-				FilterCarbide.stderr.writelines(recipeErrors)
-				errors += len(recipeErrors)
-
-			# Per-recipe summary
-			self.__errors += errors
-			self.__warnings += warnings
-			FilterCarbide.stdout.write("Errors: %d, (Total for build: %d)\n" % (errors, self.__errors))
-			FilterCarbide.stdout.write("Warnings: %d, (Total for build: %d)\n\n" % (warnings, self.__warnings))
-			self.__recipe = None
-
-		return True
-	
-	def close(self):
-		FilterCarbide.stdout.write("Overall Errors: %d\n" % self.__errors)
-		FilterCarbide.stdout.write("Overall Warnings: %d\n\n" % self.__warnings)
-
-		return True if self.__errors == 0 else False
-
+#
+# 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: 
+# Format Raptor verbose log output for the Carbide IDE
+#
+
+
+import os
+import re
+import sys
+import raptor
+import filter_interface
+import filter_utils
+
+
+class FilterCarbide(filter_interface.Filter):
+	"""Carbide IDE filter
+	Strips most verbose output leaving tools calls, tool output and formatted errors/warnings."""
+	
+	# ignore all general, benign, make output
+	ignore = re.compile('(make(\.exe)?: Nothing to be done for \`.+\'|make(\.exe)?: \[.+\] Error \d+ \(ignored\)|.*make(.exe)?\[\d\]: (Entering|Leaving) directory \`.+\')')
+	
+	stdout = filter_utils.AutoFlushedStream(sys.stdout)
+	stderr = filter_utils.AutoFlushedStream(sys.stderr)
+	
+	recipeFactory = filter_utils.RecipeFactory()
+	
+	def __init__(self):
+		self.__errors = 0
+		self.__warnings = 0
+		self.__recipe = None
+
+	def open(self, aRaptorInstance):
+		return True
+		
+	def write(self, aLine):
+		"""Process output on the fly and format appropriately for the Carbide IDE.
+		Most verbose output is discarded leaving tools calls, tool output and formatted errors
+		and warnings.
+		Identified errors go to stderr so that they will be highlighted in the IDE console."""
+		
+		if FilterCarbide.ignore.match(aLine):
+			return
+		
+		logHeader = filter_utils.logHeader.match(aLine)
+		if logHeader:
+			FilterCarbide.stdout.write("sbs version: " + logHeader.group("version")+"\n\n")
+			return
+		
+		clean = filter_utils.clean.match(aLine)
+		if clean:
+			for file in clean.group("removals").split():
+				FilterCarbide.stdout.write("clean: " + file + "\n")
+			return
+		
+		exports = filter_utils.exports.match(aLine)
+		if exports:
+			FilterCarbide.stdout.write("export: " + exports.group("source") + " to " + exports.group("destination") + "\n")
+			return
+		
+		
+		if self.__recipe:
+			self.__recipe.addLine(aLine)
+			
+			if self.__recipe.isComplete():
+				for call in self.__recipe.getCalls():
+					FilterCarbide.stdout.write(call + "\n")				
+		else:		
+			logTag = filter_utils.logTag.match(aLine)
+			if logTag:
+				tagName = logTag.group("name")			
+				if tagName == "recipe":
+					if self.__recipe:
+						self.__recipe.addLine(aLine)
+					else:
+						self.__recipe = FilterCarbide.recipeFactory.newRecipe(aLine)						
+				elif tagName == "error":
+					self.__errors += 1
+					FilterCarbide.stderr.write("Error: " + filter_utils.logTag.sub("", aLine) + "\n")
+				elif tagName == "warning":
+					self.__warnings += 1
+					FilterCarbide.stdout.write("Warning: " + filter_utils.logTag.sub("", aLine) + "\n")
+				# we're not interested in any other tagged output
+				return
+			else:
+				# Not a recipe, and not tagged output that we know about.
+				# Output this anyway, just in case it's something important
+				FilterCarbide.stdout.write(aLine)
+		
+		
+		if self.__recipe and self.__recipe.isComplete():
+			errors = 0
+			warnings = 0			
+
+			recipeOutput = self.__recipe.getOutput()
+			recipeWarnings = self.__recipe.getWarnings()
+			recipeErrors = self.__recipe.getErrors()
+
+			if len(recipeOutput):
+				FilterCarbide.stdout.writelines(recipeOutput)		
+			if len(recipeWarnings):
+				FilterCarbide.stdout.writelines(recipeWarnings)
+				warnings += len(recipeWarnings)
+			if len(recipeErrors):
+				FilterCarbide.stderr.writelines(recipeErrors)
+				errors += len(recipeErrors)
+
+			# Per-recipe summary
+			self.__errors += errors
+			self.__warnings += warnings
+			FilterCarbide.stdout.write("Errors: %d, (Total for build: %d)\n" % (errors, self.__errors))
+			FilterCarbide.stdout.write("Warnings: %d, (Total for build: %d)\n\n" % (warnings, self.__warnings))
+			self.__recipe = None
+
+		return True
+	
+	def close(self):
+		FilterCarbide.stdout.write("Overall Errors: %d\n" % self.__errors)
+		FilterCarbide.stdout.write("Overall Warnings: %d\n\n" % self.__warnings)
+
+		return (self.__errors == 0)
--- a/sbsv2/raptor/python/plugins/filter_checksource.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/plugins/filter_checksource.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,376 +1,376 @@
-#
-# 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: 
-#
-
-import raptor_utilities
-import os
-import re
-import sys
-import filter_interface
-import xml.parsers.expat
-import raptor
-import generic_path
-import tempfile
-
-# This filter has not been tested on linux
-if not raptor_utilities.getOSPlatform().startswith("linux"):
-	
-	# Compares the two paths, and reports the differences highlighted by a "^" character
-	# Output Generated will be like this:
-	# Reference in metadata -> C:/foo/bar/cat.cpp
-	# 			               -------^-------^-- 
-	# Reference in metadata -> C:/foo/Bar/cat.Cpp
-	def reportcsdifference(path1, path2):
-		
-		same = "-"
-		different = "^"
-		space = ' '
-		metadataString = 'Reference in metadata -> '
-		ondiskString   = 'Actual case on disk   -> '
-		
-		sys.stderr.write(metadataString + path2 +"\n")
-		separator = ""
-		for i, e in enumerate(path1):
-			try:
-				if e != path2[i]:
-					separator += different
-				else:
-					separator += same
-			except IndexError:
-				separator += '*'
-
-		separator += different * (len(path1)-len(path2))
-		
-		sys.stderr.write(space*len(metadataString) + separator +"\n") # Print the separator in alignment with the metadataString
-		sys.stderr.write(ondiskString + path1 + "\n")
-
-	class FilterCheckSource(filter_interface.Filter):
-
-		def open(self, raptor_instance):
-			self.raptor = raptor_instance
-			self.ok = True
-			self.errors = 0
-			self.checked = []
-			self.check = raptor_instance.doCheck
-			self.casechecker = CheckCase()
-			
-			# Expat Parser initialisation
-			self.p = xml.parsers.expat.ParserCreate()
-			self.p.StartElementHandler = self.startelement # Handles opening XML tags
-			self.p.EndElementHandler = self.endelement # Handles closing XML tags
-			self.p.CharacterDataHandler = self.chardata # Handles data between opening/closing tags
-			
-			# Regex initialisation
-			self.rvctdependfinder = re.compile("--depend\s+(.*?d)(?:\s+|$)", re.IGNORECASE|re.DOTALL)
-			self.cwdependfinder = re.compile("#'\s+(.*?\.dep)", re.IGNORECASE|re.DOTALL)
-			
-			# Data to be passed to case checkers
-			self.currentmmp = ""
-			self.currentbldinf = ""
-			self.currentconfig = ""
-			
-			self.filestocheck = []
-			
-			# Need this flag for the chardata method that does not have the name of the
-			# current XML element passed to it as a parameter.
-			self.infiletag = False
-			
-			# Create a temporary file to record all dependency files. We can only parse those after 
-			# make has finished running all the compile commands and by definition these
-			# files should therefore exist.
-			try:
-				self.tmp = tempfile.TemporaryFile()
-			except:
-				sys.stderr.write("sbs: could not create temporary file for FilterClean\n")
-				self.ok = False
-			
-			return self.ok
-
-		def write(self, text):
-			# Slightly nasty that we have to "ignore" exceptions, but the xml parser 
-			# generates this when it encounters non-xml lines (like make: nothing to be done for 'export')
-			try:
-				self.p.Parse(text.rstrip())	
-			except xml.parsers.expat.ExpatError:
-				pass
-
-			return self.ok
-
-		def saveitem(self, path):
-			"put path into a temporary file."
-			try:
-				self.tmp.write(path + "\n")
-			except:
-				sys.stderr.write("sbs: could not write temporary file in FilterCheckSource\n")
-				self.ok = False
-
-		def startelement(self, name, attrs):
-			# Check the source code cpp files - obtained from the "source" 
-			# attribute of compile and other tags 
-			if 'source' in attrs.keys():
-				if attrs['source'] != "":
-					self.filestocheck.append(attrs['source'])
-			
-			# Record the current metadata files and config
-			if name == "clean":
-				self.currentmmp = attrs["mmp"]
-				self.currentbldinf = attrs["bldinf"]
-				self.currentconfig = attrs["config"]
-			
-			# Indicates we are in a <file> element
-			if name == "file":
-				# Need to use a flag to indicate that we are processing a file tag
-				self.infiletag = True
-		
-		def chardata(self, data):
-			# Strip quotes from data
-			unquoteddata = data.strip("\"\'")
-			
-			# Use a flag to determine that we are processing a file tag since this method
-			# doesn't receive the "name" argument that startelement/endelement
-			if self.infiletag:
-				self.filestocheck.append(unquoteddata)
-				
-				# Also write dependency file names to temp file to parse the 
-				# contents of these at the end
-				if unquoteddata.endswith(".d") or unquoteddata.endswith(".dep"):
-					self.saveitem(unquoteddata)
-			
-			# RVCT depends files
-			# Outside of file tags, chardata will be called on CDATA which contains
-			# compiler calls, hence we parse these for the "--depend" option to extract
-			# the .d file.
-			if "--depend" in data:
-				result =  self.rvctdependfinder.findall(data)
-				for res in result:
-					self.saveitem(res)
-			
-			# CW toolchain depends files
-			# As for RVCT, chardata will be called on CDATA which contains compiler calls, 
-			# hence we parse these for file names ending in .dep after the sequence #, ' and 
-			# a space. The win32.flm munges the contents of these files around so we are really
-			# interested in the .o.d files - these have the same path as the .dep files but 
-			# with the extension changed to .o.d from .dep.
-			if ".dep" in data:
-				result = self.cwdependfinder.findall(data)
-				for res in result:
-					self.saveitem(res.replace(".dep", ".o.d"))
-			
-		def endelement(self, name):
-			# Blank out the mmp, bldinf and config for next clean tag (in case it has any blanks)
-			if name == "clean":
-				self.currentmmp = ""
-				self.currentbldinf = ""
-				self.currentconfig = ""
-			
-			if name == "file":
-				self.infiletag = False
-			
-			if len(self.filestocheck) > 0:
-				# Check the found file(s)
-				for filename in self.filestocheck:
-					self.checksource(filename)
-				
-				# Reset list so as not to re-check already checked files
-				self.filestocheck = []
-				
-		def close(self):			
-			return self.ok
-
-		def summary(self):
-			
-			depparser = DependenciesParser()
-			dependenciesfileset = set() # Stores the files listed inside depdendency files
-			deps = [] # Stores dependency (.d and .dep) files
-			
-			try:
-				self.tmp.flush()	# write what is left in the buffer
-				self.tmp.seek(0)	# rewind to the beginning
-				
-				for line in self.tmp.readlines():
-					path = line.strip()
-					
-					# Only try to parse the file if it exists as a file, and if we haven't done so 
-					# already (store the list of parsed files in the set "dependenciesfileset"
-					if os.path.isfile(path) and not path in dependenciesfileset:
-						dependenciesfileset.add(path)
-						
-						# Here we parse each dependency file and form a list of the prerequisites contained therein
-						dependencyfilelines = depparser.readdepfilelines(path) # Read the lines
-						dependencyfilestr = depparser.removelinecontinuation(dependencyfilelines) # Join them up
-						dependencyfiles = depparser.getdependencies(dependencyfilestr) # Get prerequisites
-						deps.extend(dependencyfiles) # Add to list
-					else:
-						sys.stdout.write("\t"  + path + " does not exist\n")
-						
-				self.tmp.close()	# This also deletes the temporary file
-				
-				# Make a set of the prerequisites listed in the dependency files
-				# so we only check each one once
-				depset = set(deps)
-				deplistnodups = list(depset)
-				
-				# Do the check for each file 	
-				for dep in deplistnodups:
-					dep = os.path.normpath(dep).replace('\\', '/')
-					self.checksource(dep)
-					
-			except Exception, e:
-				sys.stderr.write("sbs: could not access temporary file for FilterClean\n")
-				
-			if self.errors == 0:
-				sys.stdout.write("No checksource errors found\n")
-			else:
-				sys.stdout.write("\n %d checksource errors found in the build\n" % self.errors)
-			
-		
-		def checksource(self, path):
-			normedpath = path.replace("\"", "") # Remove quoting
-			
-			if normedpath not in self.checked:
-				self.checked.append(normedpath)
-				try:
-					realpath = self.casechecker.checkcase(normedpath)
-				except IOError, e:
-					# file does not exist so just return
-					return
-										
-				if not realpath == normedpath and realpath != "":
-					self.ok = False
-					self.errors += 1
-					sys.stderr.write("\nChecksource Failure:\n")
-					reportcsdifference(realpath, normedpath)
-
-	class CheckCase(object):
-		"""Used to check the case of a given path matches the file system.  
-		Caches previous lookups to reduce disk IO and improve performance"""
-		
-		def __init__(self):
-			self.__dirsCache = {} # a hash containing the directory structure, in the same case as the file system
-		
-		def checkcase(self, path):
-			"""Checks the path matches the file system"""
-			
-			path = os.path.normpath(path)
-			path = path.replace('\\', '/')
-			
-			if not os.path.exists(path):
-				raise IOError, path + " does not exist"
-				
-			parts = path.split('/')
-			
-			dirBeingChecked = parts.pop(0) + "/"
-			
-			cacheItem = self.__dirsCache
-			
-			for part in parts:
-				if not self.checkkeyignorecase(cacheItem, part):
-				
-					dirItems = os.listdir(dirBeingChecked)
-					
-					found = False
-					
-					for dirItem in dirItems:
-						if os.path.isdir(os.path.join(dirBeingChecked, dirItem)):
-							if not cacheItem.has_key(dirItem):
-								cacheItem[dirItem] = {}
-							
-							if not found:
-								# Check if there is a dir match
-								if re.search("^" + part + "$", dirItem, re.IGNORECASE):
-									found = True
-									
-									cacheItem = cacheItem[dirItem]
-									
-									dirBeingChecked = os.path.join(dirBeingChecked, dirItem).replace('\\', '/')
-						else:
-							cacheItem[dirItem] = 1
-					
-							if not found:
-								# Check if there is a dir match
-								if re.search("^" + part + "$", dirItem, re.IGNORECASE):
-									found = True
-									
-									return os.path.join(dirBeingChecked, dirItem).replace('\\', '/')                         
-				
-				else:
-					if os.path.isdir(os.path.join(dirBeingChecked, part)):
-						cacheItem = cacheItem[part]
-				
-					dirBeingChecked = os.path.join(dirBeingChecked, part).replace('\\', '/')
-	
-			return dirBeingChecked
-	
-		def checkkeyignorecase(self, dictionary, keyToFind):
-			for key in dictionary.keys():
-				if re.search("^" + keyToFind + "$", key, re.IGNORECASE):
-					
-					if not keyToFind == key:
-						return False
-					
-					return True
-			
-			return False
-
-	class DependenciesParser(object):
-		
-		def __init__(self):
-			pass # Nop - nothing to do for init
-		
-		def readdepfilelines(self, dotdfile):
-			""" Read the lines from a Make dependency file and return them as a list """
-			lines = []
-			try:
-				fh = open(dotdfile, "r")
-			except IOError, e:
-				print "Error: Failed to open file \"%s\": %s" % (dotdfile, e.strerror)
-			except Exception, e:
-				print "Error: Unknown error: %s" % str(e)
-			else:
-				lines = fh.readlines()
-				fh.close()
-				
-			return lines
-		
-		def removelinecontinuation(self, lineslist):
-			""" Remove line continuation chararacters '\\' from the end of any lines in  
-			the list that have them and return a string with lines joined together """
-			str = " ".join(lineslist).replace('\\\n','')
-			return str
-		
-		def getdependencies(self, dotdfilestring):
-			""" Splits the multi-lined string dotdfilestring and performs a regexp
-			match on files to the right of a : on each line """
-			
-			# Strip whitespace at the start of the string	
-			lines = dotdfilestring.lstrip().split("\n")
-			
-			dependencyset = set() # Create a set to skip duplicates
-			for line in lines:
-				# Split on whitespace that is *not* preceeded by a \ - i.e. 
-				# don't split on escaped spaces.
-				lineparts = re.split("(?<!\\\\)\s+", line)
-				
-				# Drop element 0 as this will be the target of each rule
-				lineparts = lineparts[1:]
-				
-				for linepart in lineparts:
-					# Some of the line parts are empty, so skip those
-					if linepart != "":
-						dependencyset.add(linepart)
-			
-			# Create list to return from the initial set
-			files = list(dependencyset)
-			return files  
+#
+# 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: 
+#
+
+import raptor_utilities
+import os
+import re
+import sys
+import filter_interface
+import xml.parsers.expat
+import raptor
+import generic_path
+import tempfile
+
+# This filter has not been tested on linux
+if not raptor_utilities.getOSPlatform().startswith("linux"):
+	
+	# Compares the two paths, and reports the differences highlighted by a "^" character
+	# Output Generated will be like this:
+	# Reference in metadata -> C:/foo/bar/cat.cpp
+	# 			               -------^-------^-- 
+	# Reference in metadata -> C:/foo/Bar/cat.Cpp
+	def reportcsdifference(path1, path2):
+		
+		same = "-"
+		different = "^"
+		space = ' '
+		metadataString = 'Reference in metadata -> '
+		ondiskString   = 'Actual case on disk   -> '
+		
+		sys.stderr.write(metadataString + path2 +"\n")
+		separator = ""
+		for i, e in enumerate(path1):
+			try:
+				if e != path2[i]:
+					separator += different
+				else:
+					separator += same
+			except IndexError:
+				separator += '*'
+
+		separator += different * (len(path1)-len(path2))
+		
+		sys.stderr.write(space*len(metadataString) + separator +"\n") # Print the separator in alignment with the metadataString
+		sys.stderr.write(ondiskString + path1 + "\n")
+
+	class FilterCheckSource(filter_interface.Filter):
+
+		def open(self, raptor_instance):
+			self.raptor = raptor_instance
+			self.ok = True
+			self.errors = 0
+			self.checked = []
+			self.check = raptor_instance.doCheck
+			self.casechecker = CheckCase()
+			
+			# Expat Parser initialisation
+			self.p = xml.parsers.expat.ParserCreate()
+			self.p.StartElementHandler = self.startelement # Handles opening XML tags
+			self.p.EndElementHandler = self.endelement # Handles closing XML tags
+			self.p.CharacterDataHandler = self.chardata # Handles data between opening/closing tags
+			
+			# Regex initialisation
+			self.rvctdependfinder = re.compile("--depend\s+(.*?d)(?:\s+|$)", re.IGNORECASE|re.DOTALL)
+			self.cwdependfinder = re.compile("#'\s+(.*?\.dep)", re.IGNORECASE|re.DOTALL)
+			
+			# Data to be passed to case checkers
+			self.currentmmp = ""
+			self.currentbldinf = ""
+			self.currentconfig = ""
+			
+			self.filestocheck = []
+			
+			# Need this flag for the chardata method that does not have the name of the
+			# current XML element passed to it as a parameter.
+			self.infiletag = False
+			
+			# Create a temporary file to record all dependency files. We can only parse those after 
+			# make has finished running all the compile commands and by definition these
+			# files should therefore exist.
+			try:
+				self.tmp = tempfile.TemporaryFile()
+			except:
+				sys.stderr.write("sbs: could not create temporary file for FilterClean\n")
+				self.ok = False
+			
+			return self.ok
+
+		def write(self, text):
+			# Slightly nasty that we have to "ignore" exceptions, but the xml parser 
+			# generates this when it encounters non-xml lines (like make: nothing to be done for 'export')
+			try:
+				self.p.Parse(text.rstrip())	
+			except xml.parsers.expat.ExpatError:
+				pass
+
+			return self.ok
+
+		def saveitem(self, path):
+			"put path into a temporary file."
+			try:
+				self.tmp.write(path + "\n")
+			except:
+				sys.stderr.write("sbs: could not write temporary file in FilterCheckSource\n")
+				self.ok = False
+
+		def startelement(self, name, attrs):
+			# Check the source code cpp files - obtained from the "source" 
+			# attribute of compile and other tags 
+			if 'source' in attrs.keys():
+				if attrs['source'] != "":
+					self.filestocheck.append(attrs['source'])
+			
+			# Record the current metadata files and config
+			if name == "clean":
+				self.currentmmp = attrs["mmp"]
+				self.currentbldinf = attrs["bldinf"]
+				self.currentconfig = attrs["config"]
+			
+			# Indicates we are in a <file> element
+			if name == "file":
+				# Need to use a flag to indicate that we are processing a file tag
+				self.infiletag = True
+		
+		def chardata(self, data):
+			# Strip quotes from data
+			unquoteddata = data.strip("\"\'")
+			
+			# Use a flag to determine that we are processing a file tag since this method
+			# doesn't receive the "name" argument that startelement/endelement
+			if self.infiletag:
+				self.filestocheck.append(unquoteddata)
+				
+				# Also write dependency file names to temp file to parse the 
+				# contents of these at the end
+				if unquoteddata.endswith(".d") or unquoteddata.endswith(".dep"):
+					self.saveitem(unquoteddata)
+			
+			# RVCT depends files
+			# Outside of file tags, chardata will be called on CDATA which contains
+			# compiler calls, hence we parse these for the "--depend" option to extract
+			# the .d file.
+			if "--depend" in data:
+				result =  self.rvctdependfinder.findall(data)
+				for res in result:
+					self.saveitem(res)
+			
+			# CW toolchain depends files
+			# As for RVCT, chardata will be called on CDATA which contains compiler calls, 
+			# hence we parse these for file names ending in .dep after the sequence #, ' and 
+			# a space. The win32.flm munges the contents of these files around so we are really
+			# interested in the .o.d files - these have the same path as the .dep files but 
+			# with the extension changed to .o.d from .dep.
+			if ".dep" in data:
+				result = self.cwdependfinder.findall(data)
+				for res in result:
+					self.saveitem(res.replace(".dep", ".o.d"))
+			
+		def endelement(self, name):
+			# Blank out the mmp, bldinf and config for next clean tag (in case it has any blanks)
+			if name == "clean":
+				self.currentmmp = ""
+				self.currentbldinf = ""
+				self.currentconfig = ""
+			
+			if name == "file":
+				self.infiletag = False
+			
+			if len(self.filestocheck) > 0:
+				# Check the found file(s)
+				for filename in self.filestocheck:
+					self.checksource(filename)
+				
+				# Reset list so as not to re-check already checked files
+				self.filestocheck = []
+				
+		def close(self):			
+			return self.ok
+
+		def summary(self):
+			
+			depparser = DependenciesParser()
+			dependenciesfileset = set() # Stores the files listed inside depdendency files
+			deps = [] # Stores dependency (.d and .dep) files
+			
+			try:
+				self.tmp.flush()	# write what is left in the buffer
+				self.tmp.seek(0)	# rewind to the beginning
+				
+				for line in self.tmp.readlines():
+					path = line.strip()
+					
+					# Only try to parse the file if it exists as a file, and if we haven't done so 
+					# already (store the list of parsed files in the set "dependenciesfileset"
+					if os.path.isfile(path) and not path in dependenciesfileset:
+						dependenciesfileset.add(path)
+						
+						# Here we parse each dependency file and form a list of the prerequisites contained therein
+						dependencyfilelines = depparser.readdepfilelines(path) # Read the lines
+						dependencyfilestr = depparser.removelinecontinuation(dependencyfilelines) # Join them up
+						dependencyfiles = depparser.getdependencies(dependencyfilestr) # Get prerequisites
+						deps.extend(dependencyfiles) # Add to list
+					else:
+						sys.stdout.write("\t"  + path + " does not exist\n")
+						
+				self.tmp.close()	# This also deletes the temporary file
+				
+				# Make a set of the prerequisites listed in the dependency files
+				# so we only check each one once
+				depset = set(deps)
+				deplistnodups = list(depset)
+				
+				# Do the check for each file 	
+				for dep in deplistnodups:
+					dep = os.path.abspath(dep).replace('\\', '/')
+					self.checksource(dep)
+					
+			except Exception, e:
+				sys.stderr.write("sbs: FilterCheckSource failed: %s\n" % str(e))
+				
+			if self.errors == 0:
+				sys.stdout.write("No checksource errors found\n")
+			else:
+				sys.stdout.write("\n %d checksource errors found in the build\n" % self.errors)
+			
+		
+		def checksource(self, path):
+			normedpath = path.replace("\"", "") # Remove quoting
+			
+			if normedpath not in self.checked:
+				self.checked.append(normedpath)
+				try:
+					realpath = self.casechecker.checkcase(normedpath)
+				except IOError, e:
+					# file does not exist so just return
+					return
+										
+				if not realpath == normedpath and realpath != "":
+					self.ok = False
+					self.errors += 1
+					sys.stderr.write("\nChecksource Failure:\n")
+					reportcsdifference(realpath, normedpath)
+
+	class CheckCase(object):
+		"""Used to check the case of a given path matches the file system.  
+		Caches previous lookups to reduce disk IO and improve performance"""
+		
+		def __init__(self):
+			self.__dirsCache = {} # a hash containing the directory structure, in the same case as the file system
+		
+		def checkcase(self, path):
+			"""Checks the path matches the file system"""
+			
+			path = os.path.abspath(path)
+			path = path.replace('\\', '/')
+			
+			if not os.path.exists(path):
+				raise IOError, path + " does not exist"
+				
+			parts = path.split('/')
+			
+			dirBeingChecked = parts.pop(0) + "/"
+			
+			cacheItem = self.__dirsCache
+			
+			for part in parts:
+				if not self.checkkeyignorecase(cacheItem, part):
+
+					dirItems = os.listdir(dirBeingChecked)
+					
+					found = False
+					
+					for dirItem in dirItems:
+						if os.path.isdir(os.path.join(dirBeingChecked, dirItem)):
+							if not cacheItem.has_key(dirItem):
+								cacheItem[dirItem] = {}
+							
+							if not found:
+								# Check if there is a dir match
+								if re.search("^" + part + "$", dirItem, re.IGNORECASE):
+									found = True
+									
+									cacheItem = cacheItem[dirItem]
+									
+									dirBeingChecked = os.path.join(dirBeingChecked, dirItem).replace('\\', '/')
+						else:
+							cacheItem[dirItem] = 1
+					
+							if not found:
+								# Check if there is a dir match
+								if re.search("^" + part + "$", dirItem, re.IGNORECASE):
+									found = True
+									
+									return os.path.join(dirBeingChecked, dirItem).replace('\\', '/')                         
+				
+				else:
+					if os.path.isdir(os.path.join(dirBeingChecked, part)):
+						cacheItem = cacheItem[part]
+				
+					dirBeingChecked = os.path.join(dirBeingChecked, part).replace('\\', '/')
+	
+			return dirBeingChecked
+	
+		def checkkeyignorecase(self, dictionary, keyToFind):
+			for key in dictionary.keys():
+				if re.search("^" + keyToFind + "$", key, re.IGNORECASE):
+					
+					if not keyToFind == key:
+						return False
+					
+					return True
+			
+			return False
+
+	class DependenciesParser(object):
+		
+		def __init__(self):
+			pass # Nop - nothing to do for init
+		
+		def readdepfilelines(self, dotdfile):
+			""" Read the lines from a Make dependency file and return them as a list """
+			lines = []
+			try:
+				fh = open(dotdfile, "r")
+			except IOError, e:
+				print "Error: Failed to open file \"%s\": %s" % (dotdfile, e.strerror)
+			except Exception, e:
+				print "Error: Unknown error: %s" % str(e)
+			else:
+				lines = fh.readlines()
+				fh.close()
+				
+			return lines
+		
+		def removelinecontinuation(self, lineslist):
+			""" Remove line continuation chararacters '\\' from the end of any lines in  
+			the list that have them and return a string with lines joined together """
+			str = " ".join(lineslist).replace('\\\n','')
+			return str
+		
+		def getdependencies(self, dotdfilestring):
+			""" Splits the multi-lined string dotdfilestring and performs a regexp
+			match on files to the right of a : on each line """
+			
+			# Strip whitespace at the start of the string	
+			lines = dotdfilestring.lstrip().split("\n")
+			
+			dependencyset = set() # Create a set to skip duplicates
+			for line in lines:
+				# Split on whitespace that is *not* preceeded by a \ - i.e. 
+				# don't split on escaped spaces.
+				lineparts = re.split("(?<!\\\\)\s+", line)
+				
+				# Drop element 0 as this will be the target of each rule
+				lineparts = lineparts[1:]
+				
+				for linepart in lineparts:
+					# Some of the line parts are empty, so skip those
+					if linepart != "":
+						dependencyset.add(linepart)
+			
+			# Create list to return from the initial set
+			files = list(dependencyset)
+			return files  
--- a/sbsv2/raptor/python/plugins/filter_clean.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/plugins/filter_clean.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,170 +1,150 @@
-#
-# 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: 
-# Filter class for doing CLEAN, CLEANEXPORT and REALLYCLEAN efficiently.
-#
-
-import os
-import sys
-import tempfile
-import filter_interface
-
-class FilterClean(filter_interface.Filter):
-	
-	def open(self, params):
-		"initialise"
-		
-		targets = [x.lower() for x in params.targets]
-		
-		self.removeExports = ("cleanexport" in targets or "reallyclean" in targets)
-		self.removeTargets = ("clean" in targets or "reallyclean" in targets)
-		
-		self.ok = True
-		
-		# create a temporary file to record all the exports and directories
-		# in. We can only remove those after "make" has finished running all
-		# the CLEAN targets.
-		try:
-			self.tmp = tempfile.TemporaryFile()
-		except:
-			sys.stderr.write("sbs: could not create temporary file for FilterClean\n")
-			self.ok = False
-		
-		return self.ok
-	
-	
-	def write(self, text):
-		"process some log text"
-		
-		for line in text.splitlines():
-		
-			if self.removeTargets:
-				if line.startswith("<file>"):
-					self.doFile(line)
-				elif line.startswith("<dir>"):
-					self.doDirectory(line)
-						
-			if self.removeExports:
-				if line.startswith("<export "):
-					self.doExport(line)
-				elif line.startswith("<member>"):
-					self.doMember(line)
-				elif line.startswith("<zipmarker>"):
-					self.doZipMarker(line)
-				
-		return self.ok
-	
-	
-	def summary(self):
-		"finish off"
-		
-		# remove files, remembering directories
-		dirs = set()
-		
-		try:
-			self.tmp.flush()	# write what is left in the buffer
-			self.tmp.seek(0)	# rewind to the beginning
-			
-			for line in self.tmp.readlines():
-				path = line.strip()
-				
-				if os.path.isfile(path):
-					self.removeFile(path)
-					
-				elif os.path.isdir(path):
-					dirs.add(path)
-					
-			self.tmp.close()	# this also deletes the temporary file
-		except:
-			sys.stderr.write("sbs: could not access temporary file for FilterClean\n")
-			self.ok = False
-		
-		# finally remove (empty) directories
-		for dir in dirs:
-			try:
-				os.removedirs(dir)	# may fail if the directory has files in
-			except:
-				pass				# silently ignore all errors
-				
-		return self.ok
-
-
-	def close(self):
-		"nop"
-		
-		return self.ok
-	
-	
-	def removeFile(self, path):
-		try:
-			os.unlink(path)
-		except Exception, e:
-			sys.stderr.write("sbs: could not remove " + path + "\n")
-			sys.stderr.write(str(e) + "\n")
-		
-				
-	def saveItem(self, path):
-		"put path into a temporary file."
-		try:
-			self.tmp.write(path + "\n")
-		except:
-			sys.stderr.write("sbs: could not write temporary file in FilterClean\n")
-			self.ok = False
-	
-			
-	def doFile(self, line):
-		"remove filenames in <file> tags immediately (not .d or .dep)."
-		filename = line[6:-7]                # line is "<file>filename</file>
-		filename = filename.strip("\"\'")    # some names are quoted
-		
-		# dependency files must be deleted at the end,
-		# everything else can be deleted straight away.
-		if filename.endswith(".d") or filename.endswith(".dep"):
-			self.saveItem(filename)
-		else:
-			if os.path.isfile(filename):
-				self.removeFile(filename)
-
-
-	def doDirectory(self, line):
-		"save directories in <dir> tags for the end."
-		# assuming <dir>X</dir>
-		dirname = line[5:-6]
-		self.saveItem(dirname.strip("\"\'"))
-		
-		
-	def doExport(self, line):
-		"save exported files in <export> tags for the end."
-		# assuming <export destination='X' source='Y' />
-		filename = line[21:line.find("'", 21)]
-		self.saveItem(filename)
-		
-		
-	def doMember(self, line):
-		"save zip exports in <member> tags for the end."
-		# assuming <member>X</member>
-		filename = line[8:-9]
-		self.saveItem(filename)
-		
-		
-	def doZipMarker(self, line):
-		"Remove file in <zipmarker> tags"
-		# assuming <zipmarker>X</zipmarker>
-		filename = line[11:-12]
-		if os.path.isfile(filename):
-			self.removeFile(filename)
-
-
-# the end				
-
+#
+# 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: 
+# Filter class for doing CLEAN, CLEANEXPORT and REALLYCLEAN efficiently.
+#
+
+import os
+import sys
+import tempfile
+import filter_interface
+
+class FilterClean(filter_interface.Filter):
+	
+	def open(self, params):
+		"initialise"
+		
+		targets = [x.lower() for x in params.targets]
+		
+		self.removeExports = ("cleanexport" in targets or "reallyclean" in targets)
+		self.removeTargets = ("clean" in targets or "reallyclean" in targets)
+		
+		self.ok = True
+		
+		# create a temporary file to record all the exports and directories
+		# in. We can only remove those after "make" has finished running all
+		# the CLEAN targets.
+		try:
+			self.tmp = tempfile.TemporaryFile()
+		except:
+			sys.stderr.write("sbs: could not create temporary file for FilterClean\n")
+			self.ok = False
+		
+		return self.ok
+	
+	
+	def write(self, text):
+		"process some log text"
+		
+		for line in text.splitlines():
+		
+			if self.removeTargets:
+				if line.startswith("<file>"):
+					self.doFile(line, "file")
+				elif line.startswith("<build>"):
+					self.doFile(line, "build")
+				elif line.startswith("<resource>"):
+					self.doFile(line, "resource")
+				elif line.startswith("<bitmap>"):
+					self.doFile(line, "bitmap")
+				elif line.startswith("<stringtable>"):
+					self.doFile(line, "stringtable")
+						
+			if self.removeExports:
+				if line.startswith("<export "):
+					self.doExport(line)
+				elif line.startswith("<member>"):
+					self.doFile(line, "member")
+				elif line.startswith("<zipmarker>"):
+					self.doFile(line, "zipmarker")
+				
+		return self.ok
+	
+	
+	def summary(self):
+		"finish off"
+		
+		# remove files, remembering directories
+		dirs = set()
+		
+		try:
+			self.tmp.flush()	# write what is left in the buffer
+			self.tmp.seek(0)	# rewind to the beginning
+			
+			for line in self.tmp.readlines():
+				path = line.strip()
+				
+				if os.path.isfile(path):
+					self.removeFile(path)
+				
+				directory = os.path.dirname(path)
+				if os.path.isdir(directory):
+					dirs.add(directory)
+					
+			self.tmp.close()	# this also deletes the temporary file
+		except Exception,e:
+			sys.stderr.write("sbs: problem reading temporary file for FilterClean: %s\n" % str(e))
+			self.ok = False
+		
+		# finally remove (empty) directories
+		for dir in dirs:
+			try:
+				os.removedirs(dir)	# may fail if the directory has files in
+			except:
+				pass				# silently ignore all errors
+				
+		return self.ok
+
+
+	def close(self):
+		"nop"
+		
+		return self.ok
+	
+	
+	def removeFile(self, path):
+		try:
+			os.unlink(path)
+		except Exception, e:
+			sys.stderr.write("sbs: could not remove " + path + "\n")
+			sys.stderr.write(str(e) + "\n")
+		
+				
+	def saveItem(self, path):
+		"put path into a temporary file."
+		try:
+			self.tmp.write(path + "\n")
+		except:
+			sys.stderr.write("sbs: could not write temporary file in FilterClean\n")
+			self.ok = False
+	
+			
+	def doFile(self, line, tagname):
+		"deal with <tagname>X</tagname>"
+		
+		first = len(tagname) + 2	# line is "<tagname>filename</tagname>
+		last = -(first + 1)
+		filename = line[first:last]                
+		filename = filename.strip("\"\'")    # some names are quoted
+		self.saveItem(filename)
+				
+
+	def doExport(self, line):
+		"deal with <export destination='X' source='Y'/>"
+		filename = line[21:line.find("'", 21)]
+		self.saveItem(filename)
+
+
+# the end				
+
--- a/sbsv2/raptor/python/plugins/filter_logfile.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/plugins/filter_logfile.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,77 +1,78 @@
-#
-# 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: 
-# Filter class for filtering XML logs and generate reports
-# Will ultimately do everything that scanlog does
-#
-
-import os
-import sys
-import raptor
-import filter_interface
-
-class FilterLogfile(filter_interface.Filter):
-
-	def open(self, raptor_instance):
-		"""Open a log file for the various I/O methods to write to."""
-
-		self.raptor = raptor_instance
-		self.logFileName = self.raptor.logFileName
-		# insert the time into the log file name
-		if self.logFileName:
-			self.logFileName.path = self.logFileName.path.replace("%TIME",
-					self.raptor.timestring)
-	
-			try:
-				dirname = str(self.raptor.logFileName.Dir())
-				if dirname and not os.path.isdir(dirname):
-					os.makedirs(dirname)
-			except os.error, e:
-				if e.errno != os.errno.EEXIST:
-					sys.stderr.write("%s : error: cannot create directory %s\n" % \
-						(str(raptor.name), dirname))
-					return False
-			try:
-				self.out = open(str(self.logFileName), "w")
-			except:
-				self.out = None
-				sys.stderr.write("%s : error: cannot write log %s\n" %\
-					(str(raptor.name), self.logFileName.GetShellPath()))
-				return False
-		else:
-			self.out = sys.stdout
-
-		return True
-
-	def write(self, text):
-		"""Write text into the log file"""
-
-		self.out.write(text)
-		return True
-
-	def summary(self):
-		"""Write Summary"""
-		if self.logFileName and not self.raptor.quiet:
-			sys.stdout.write("sbs: build log in %s\n" % str(self.logFileName))
-		return False
-
-	def close(self):
-		"""Close the log file"""
-
-		try:
-			self.out.close()
-			return True
-		except:
-			self.out = None
-		return False
+#
+# 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: 
+# Filter class for filtering XML logs and generate reports
+# Will ultimately do everything that scanlog does
+#
+
+import errno
+import os
+import sys
+import raptor
+import filter_interface
+
+class FilterLogfile(filter_interface.Filter):
+
+	def open(self, raptor_instance):
+		"""Open a log file for the various I/O methods to write to."""
+
+		self.raptor = raptor_instance
+		self.logFileName = self.raptor.logFileName
+		# insert the time into the log file name
+		if self.logFileName:
+			self.logFileName.path = self.logFileName.path.replace("%TIME",
+					self.raptor.timestring)
+	
+			try:
+				dirname = str(self.raptor.logFileName.Dir())
+				if dirname and not os.path.isdir(dirname):
+					os.makedirs(dirname)
+			except os.error, e:
+				if e.errno != errno.EEXIST:
+					sys.stderr.write("%s : error: cannot create directory %s\n" % \
+						(str(raptor.name), dirname))
+					return False
+			try:
+				self.out = open(str(self.logFileName), "w")
+			except:
+				self.out = None
+				sys.stderr.write("%s : error: cannot write log %s\n" %\
+					(str(raptor.name), self.logFileName.GetShellPath()))
+				return False
+		else:
+			self.out = sys.stdout
+
+		return True
+
+	def write(self, text):
+		"""Write text into the log file"""
+
+		self.out.write(text)
+		return True
+
+	def summary(self):
+		"""Write Summary"""
+		if self.logFileName and not self.raptor.quiet:
+			sys.stdout.write("sbs: build log in %s\n" % str(self.logFileName))
+		return False
+
+	def close(self):
+		"""Close the log file"""
+
+		try:
+			self.out.close()
+			return True
+		except:
+			self.out = None
+		return False
--- a/sbsv2/raptor/python/plugins/filter_splitlog.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/plugins/filter_splitlog.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,157 +1,158 @@
-#
-# 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: 
-# Filter class for filtering XML logs and generate reports
-# Will ultimately do everything that scanlog does
-#
-
-import os
-import sys
-import raptor
-import filter_interface
-
-class FilterSplitlog(filter_interface.Filter):
-
-	def open(self, raptor_instance):
-		"""Open a log file for the various I/O methods to write to."""
-
-		self.raptor = raptor_instance
-		self.logFileName = self.raptor.logFileName
-		# insert the time into the log file name
-		if self.logFileName:
-			self.logFileName.path = self.logFileName.path.replace("%TIME",
-					self.raptor.timestring)
-	
-			try:
-				dirname = str(self.raptor.logFileName.Dir())
-				if dirname and not os.path.isdir(dirname):
-					os.makedirs(dirname)
-			except os.error, e:
-				if e.errno != os.errno.EEXIST:
-					sys.stderr.write("%s : error: cannot create directory " +
-							"%s\n" % (raptor.name, dirname))
-					return False
-			try:
-				self.out = open(str(self.logFileName), "w")
-			except:
-				self.out = None
-				sys.stderr.write("%s : error: cannot write log %s\n" %\
-					(raptor.name, self.logFileName.GetShellPath()))
-				return False
-			
-			# Add extra streams for splitting logfile
-			self.log = str(self.logFileName)
-			self.index = self.log.rfind(".")
-			# If there is no dot, append to the end
-			if self.index < 0:
-				self.index = len(self.log)
-			self.streams = [self.out]
-			
-			# Append this list for extra files
-			stream_list = ["clean", "whatlog", "recipe"]
-				
-			for stream in stream_list:
-				
-				path = self.log[:self.index] + "." + stream + \
-						self.log[self.index:]
-				try:
-					handle = open(path, "w")
-					self.streams.append(handle)
-				except:
-					self.streams.append(self.out)
-					sys.stderr.write("%s : error: cannot write log %s\n" %\
-							(str(raptor.name), path))
-			# self.out = self.streams[0]
-			self.clean = self.streams[1]
-			self.whatlog = self.streams[2]
-			self.recipe = self.streams[3]
-			self.block = self.out
-			
-		else:
-			# Change output stream to stdout and override 'write' function
-			self.out = sys.stdout
-			def stdout_write(text):
-				self.out.write(text)
-				return True
-			self.write = stdout_write
-			
-		return True
-
-
-	def write(self, text):
-		"""Write text into relevant log file"""
-		
-		for textLine in text.splitlines():
-			textLine = textLine + '\n'
-			if textLine.startswith("<?xml ") or textLine.startswith("<buildlog ") \
-					or textLine.startswith("</buildlog"):
-				for stream in self.streams:
-					stream.write(textLine)
-			# Split 'CLEAN' output into clean file
-			elif textLine.startswith("<clean"):
-				if self.block != self.out:
-					sys.stderr.write("%s : error: invalid xml. <clean> tag found " \
-							+ "before previous block closed %s\n" %\
-							(raptor.name, self.logFileName))
-				self.block = self.clean
-				self.block.write(textLine)
-				
-			# Split 'WHATLOG' output into whatlog file
-			elif textLine.startswith("<whatlog"):
-				if self.block != self.out:
-					sys.stderr.write("%s : error: invalid xml. <whatlog> tag " + \
-							"found before previous block closed\n" %\
-							(raptor.name, self.logFileName.GetShellPath()))
-				self.block = self.whatlog
-				self.block.write(textLine)
-				
-			# Split 'RECIPE' output into recipe file
-			elif textLine.startswith("<recipe"):
-				if self.block != self.out:
-					sys.stderr.write("%s : error: invalid xml. <recipe> tag " + \
-							"found before previous block closed %s\n" %\
-							(raptor.name, self.logFileName.GetShellPath()))
-				self.block = self.recipe
-				self.block.write(textLine)
-				
-			# End of block found. Reset block to standard logfile
-			elif textLine.startswith("</clean>") or textLine.startswith("</whatlog>") \
-				or textLine.startswith("</recipe>"):
-				self.block.write(textLine)
-				self.block = self.out
-			
-		# Everything else goes to logfile associated with current block
-			else:
-				self.block.write(textLine)
-		return True
-
-
-	def summary(self):
-		"""Write Summary"""
-		if self.logFileName and not self.raptor.quiet:
-			sys.stdout.write("sbs: build log in %s\n" % self.logFileName)
-		return True
-
-
-	def close(self):
-		"""Close the log file(s)"""
-
-		try:
-			self.out.close
-			for stream in self.streams:
-				stream.close()
-			return True
-		except:
-			self.out = None
-		return False
+#
+# 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: 
+# Filter class for filtering XML logs and generate reports
+# Will ultimately do everything that scanlog does
+#
+
+import errno
+import os
+import sys
+import raptor
+import filter_interface
+
+class FilterSplitlog(filter_interface.Filter):
+
+	def open(self, raptor_instance):
+		"""Open a log file for the various I/O methods to write to."""
+
+		self.raptor = raptor_instance
+		self.logFileName = self.raptor.logFileName
+		# insert the time into the log file name
+		if self.logFileName:
+			self.logFileName.path = self.logFileName.path.replace("%TIME",
+					self.raptor.timestring)
+	
+			try:
+				dirname = str(self.raptor.logFileName.Dir())
+				if dirname and not os.path.isdir(dirname):
+					os.makedirs(dirname)
+			except os.error, e:
+				if e.errno != errno.EEXIST:
+					sys.stderr.write("%s : error: cannot create directory " +
+							"%s\n" % (raptor.name, dirname))
+					return False
+			try:
+				self.out = open(str(self.logFileName), "w")
+			except:
+				self.out = None
+				sys.stderr.write("%s : error: cannot write log %s\n" %\
+					(raptor.name, self.logFileName.GetShellPath()))
+				return False
+			
+			# Add extra streams for splitting logfile
+			self.log = str(self.logFileName)
+			self.index = self.log.rfind(".")
+			# If there is no dot, append to the end
+			if self.index < 0:
+				self.index = len(self.log)
+			self.streams = [self.out]
+			
+			# Append this list for extra files
+			stream_list = ["clean", "whatlog", "recipe"]
+				
+			for stream in stream_list:
+				
+				path = self.log[:self.index] + "." + stream + \
+						self.log[self.index:]
+				try:
+					handle = open(path, "w")
+					self.streams.append(handle)
+				except:
+					self.streams.append(self.out)
+					sys.stderr.write("%s : error: cannot write log %s\n" %\
+							(str(raptor.name), path))
+			# self.out = self.streams[0]
+			self.clean = self.streams[1]
+			self.whatlog = self.streams[2]
+			self.recipe = self.streams[3]
+			self.block = self.out
+			
+		else:
+			# Change output stream to stdout and override 'write' function
+			self.out = sys.stdout
+			def stdout_write(text):
+				self.out.write(text)
+				return True
+			self.write = stdout_write
+			
+		return True
+
+
+	def write(self, text):
+		"""Write text into relevant log file"""
+		
+		for textLine in text.splitlines():
+			textLine = textLine + '\n'
+			if textLine.startswith("<?xml ") or textLine.startswith("<buildlog ") \
+					or textLine.startswith("</buildlog"):
+				for stream in self.streams:
+					stream.write(textLine)
+			# Split 'CLEAN' output into clean file
+			elif textLine.startswith("<clean"):
+				if self.block != self.out:
+					sys.stderr.write("%s : error: invalid xml. <clean> tag found " \
+							+ "before previous block closed %s\n" %\
+							(raptor.name, self.logFileName))
+				self.block = self.clean
+				self.block.write(textLine)
+				
+			# Split 'WHATLOG' output into whatlog file
+			elif textLine.startswith("<whatlog"):
+				if self.block != self.out:
+					sys.stderr.write("%s : error: invalid xml. <whatlog> tag " + \
+							"found before previous block closed\n" %\
+							(raptor.name, self.logFileName.GetShellPath()))
+				self.block = self.whatlog
+				self.block.write(textLine)
+				
+			# Split 'RECIPE' output into recipe file
+			elif textLine.startswith("<recipe"):
+				if self.block != self.out:
+					sys.stderr.write("%s : error: invalid xml. <recipe> tag " + \
+							"found before previous block closed %s\n" %\
+							(raptor.name, self.logFileName.GetShellPath()))
+				self.block = self.recipe
+				self.block.write(textLine)
+				
+			# End of block found. Reset block to standard logfile
+			elif textLine.startswith("</clean>") or textLine.startswith("</whatlog>") \
+				or textLine.startswith("</recipe>"):
+				self.block.write(textLine)
+				self.block = self.out
+			
+		# Everything else goes to logfile associated with current block
+			else:
+				self.block.write(textLine)
+		return True
+
+
+	def summary(self):
+		"""Write Summary"""
+		if self.logFileName and not self.raptor.quiet:
+			sys.stdout.write("sbs: build log in %s\n" % self.logFileName)
+		return True
+
+
+	def close(self):
+		"""Close the log file(s)"""
+
+		try:
+			self.out.close
+			for stream in self.streams:
+				stream.close()
+			return True
+		except:
+			self.out = None
+		return False
--- a/sbsv2/raptor/python/plugins/filter_squashlog.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/plugins/filter_squashlog.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,108 +1,108 @@
-#
-# 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: 
-# Squash a raptor log file by removing commands from successful recipes
-#
-
-import os
-import sys
-import raptor
-import filter_interface
-
-class FilterSquashlog(filter_interface.Filter):
-	
-	def __init__(self):
-		self.__inRecipe = False
-
-	def open(self, raptor_instance):
-		"""Open a log file for the various I/O methods to write to."""
-		
-		if raptor_instance.logFileName == None:
-			self.out = sys.stdout
-		else:	
-			try:
-				dirname = str(raptor_instance.logFileName.Dir())
-				if dirname and not os.path.isdir(dirname):
-					os.makedirs(dirname)
-			except:
-				sys.stderr.write(str(raptor.name) + \
-						": error: cannot create directory %s\n", dirname)
-				return False
-			
-			try:
-				logname = str(raptor_instance.logFileName)
-				self.out = open(logname, "w")
-			except:
-				self.out = None
-				sys.stderr.write(str(raptor.name) + \
-						": error: cannot write log %s\n", \
-						str(raptor_instance.logFileName))
-				return False
-		
-		return True
-		
-	def write(self, line):
-		"""Write text into a squashed log file by removing commands from successful recipes"""
-		
-		# escape % characters otherwise print will fail
-		line = line.replace("%", "%%")
-		
-		# detect the start of a recipe
-		if line.startswith("<recipe "):
-			self.__inRecipe = True
-			self.__recipeLines = [line]
-			self.__squashRecipe = True
-			return
-		
-		# detect the status report from a recipe
-		if line.startswith("<status "):
-			if not "exit='ok'" in line:
-				# only squash ok recipes
-				self.__squashRecipe = False
-			self.__recipeLines.append(line)
-			return
-		
-		# detect the end of a recipe
-		if line.startswith("</recipe>"):
-			# print the recipe
-			if self.__squashRecipe:
-				for text in self.__recipeLines:
-					if not text.startswith("+"):
-						self.out.write(text)
-			else:
-				for text in self.__recipeLines:
-					self.out.write(text)
-			
-			self.out.write(line)
-			self.__inRecipe = False
-			return
-
-		# remember the lines during a recipe
-		if self.__inRecipe:
-			self.__recipeLines.append(line)	
-		else:
-			# print all lines outside a recipe 
-			self.out.write(line)
-			
-		return True
-	
-	def close(self):
-		"""Close the log file"""
-		
-		try:
-			self.out.close()
-			return True
-		except:
-			self.out = None
-		return False
+#
+# 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: 
+# Squash a raptor log file by removing commands from successful recipes
+#
+
+import os
+import sys
+import raptor
+import filter_interface
+
+class FilterSquashlog(filter_interface.Filter):
+	
+	def __init__(self):
+		self.__inRecipe = False
+
+	def open(self, raptor_instance):
+		"""Open a log file for the various I/O methods to write to."""
+		
+		if raptor_instance.logFileName == None:
+			self.out = sys.stdout
+		else:	
+			try:
+				dirname = str(raptor_instance.logFileName.Dir())
+				if dirname and not os.path.isdir(dirname):
+					os.makedirs(dirname)
+			except:
+				sys.stderr.write(str(raptor.name) + \
+						": error: cannot create directory %s\n", dirname)
+				return False
+			
+			try:
+				logname = str(raptor_instance.logFileName)
+				self.out = open(logname, "w")
+			except:
+				self.out = None
+				sys.stderr.write(str(raptor.name) + \
+						": error: cannot write log %s\n", \
+						str(raptor_instance.logFileName))
+				return False
+		
+		return True
+		
+	def write(self, line):
+		"""Write text into a squashed log file by removing commands from successful recipes"""
+		
+		# escape % characters otherwise print will fail
+		line = line.replace("%", "%%")
+		
+		# detect the start of a recipe
+		if line.startswith("<recipe "):
+			self.__inRecipe = True
+			self.__recipeLines = [line]
+			self.__squashRecipe = True
+			return
+		
+		# detect the status report from a recipe
+		if line.startswith("<status "):
+			if not "exit='ok'" in line:
+				# only squash ok recipes
+				self.__squashRecipe = False
+			self.__recipeLines.append(line)
+			return
+		
+		# detect the end of a recipe
+		if line.startswith("</recipe>"):
+			# print the recipe
+			if self.__squashRecipe:
+				for text in self.__recipeLines:
+					if not text.startswith("+"):
+						self.out.write(text)
+			else:
+				for text in self.__recipeLines:
+					self.out.write(text)
+			
+			self.out.write(line)
+			self.__inRecipe = False
+			return
+
+		# remember the lines during a recipe
+		if self.__inRecipe:
+			self.__recipeLines.append(line)	
+		else:
+			# print all lines outside a recipe 
+			self.out.write(line)
+			
+		return True
+	
+	def close(self):
+		"""Close the log file"""
+		
+		try:
+			self.out.close()
+			return True
+		except:
+			self.out = None
+		return False
--- a/sbsv2/raptor/python/plugins/filter_terminal.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/plugins/filter_terminal.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,422 +1,457 @@
-#
-# 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: 
-# Filter class for filtering XML logs and generating reports
-# Prints errors and warnings to stdout
-#
-
-import sys
-import raptor
-import filter_interface
-import generic_path
-import os
-import os.path
-import re
-
-class Recipe(object):
-	"""State machine that parses a recipe
-	"""
-
-	suppress = []
-	warningRE = re.compile("^.*((Warning:)|(MAKEDEF WARNING:)) .*$", re.DOTALL | re.M | re.I)
-	infoRE = None
-	name = [ "default" ]
-	recipes = []
-
-	def __init__(self, text):
-		self.suppress = self.__class__.suppress
-		self.text = text
-		self.warningRE = Recipe.warningRE
-	
-	def warnings(self):
-		return self.warningRE.findall(self.text)
-
-	def info(self):
-		if self.infoRE:
-			return self.infoRE.findall(self.text)
-		else:
-			return []
-
-	@classmethod			
-	def factory(cls, name, text):
-		for r in Recipe.recipes:
-			if name in r.name:
-				return r(text)
-		return Recipe(text)
-	
-
-class MwLinkerRecipe(Recipe):
-	suppress = [ 
-		re.compile(
-r"^mwldsym2: warning: Cannot locate library \"MSL_All_Static_MSE_Symbian\" specified in #pragma comment\(lib,...\)$"
-r"[\n\r]*mwldsym2: warning: referenced from.*$"
-r"[\n\r]*mwldsym2: warning: Option 'Use default libraries' is enabled but linker used.*$"
-r"[\n\r]*mwldsym2: warning: runtime library from MW\[...\]LibraryFiles \(msl_all_static_mse_symbian_d.lib\);$"
-r"[\n\r]*mwldsym2: warning: this indicates a potential settings/libraries mismatch.*$"
-		, re.M)
-		, re.compile(
-r"^mwldsym2.exe: warning: Multiply defined symbol: ___get_MSL_init_count in.*$"
-r"[\n\r]*mwldsym2.exe: warning: files uc_cwhelp.obj \(.*\), startup.win32.c.obj \(msl_all_static_mse_symbian_d.lib\),.*$"
-r"[\n\r]*mwldsym2.exe: warning: keeping definition in startup.win32.c.obj.*$"
-		, re.M )
-		, re.compile(
-r"^mwldsym2.exe: warning: Option 'Use default libraries' is enabled but linker used.*$"
-r"[\n\r]*mwldsym2.exe: warning: runtime library from MW\[...\]LibraryFiles \(msl_all_static_mse_symbian_d.lib\);.*$"
-r"[\n\r]*mwldsym2.exe: warning: this indicates a potential settings/libraries mismatch.*$"
-	, re.M)
-	]
-	name = [ "win32stagetwolink", "win32simplelink" ]
-
-	def warnings(self):
-		edited = self.text
-		for s in MwLinkerRecipe.suppress:
-			edited = s.sub("", edited)
-		return Recipe.warningRE.findall(edited)
-
-Recipe.recipes.append(MwLinkerRecipe)
-
-
-class FreezeRecipe(Recipe):
-	name = [ "freeze" ]
-	warningRE = re.compile("^(WARNING:) .*$", re.DOTALL | re.M | re.I)
-	infoRE = re.compile("^(EFREEZE:) .*$", re.DOTALL | re.M | re.I)
-
-	def __init__(self, text):
-		Recipe.__init__(self, text)
-		self.warningRE = FreezeRecipe.warningRE
-		self.infoRE = FreezeRecipe.infoRE
-
-Recipe.recipes.append(FreezeRecipe)
-
-
-
-class FilterTerminal(filter_interface.Filter):
-
-	attribute_re = re.compile("([a-z][a-z0-9]*)='([^']*)'",re.I)
-	maxdots = 40 # if one prints dots then don't print masses
-	recipelinelimit = 200 # don't scan ultra-long recipes in case we run out of memory
-
-	# recipes that we think most users are interested in
-	# and the mapping that we will use to output them as
-	docare = {
-		"asmcompile" : "asmcompile" ,
-		"compile" : "compile" ,
-		"postlink" : "target",
-		"resourcecompile" : "resource",
-		"genstringtable" : "strtable",
-		"tem" : "tem",
-		"bitmapcompile" : "bitmap",
-		"bitmapcopy" : "bitmapcopy",
-		"win32compile2object" : "compile",
-		"win32stagetwolink" : "target",
-		"win32simplelink" : "target",
-		"tools2install" : "target",
-		"compile2object" : "compile",
-		"msvctoolsinstall" : "target",
-		"msvctoolscompile" : "compile",
-		"freeze" : "freeze",
-		"win32archive" : "target"
-	}
-
-	# Determine the width of the largest mapped recipe name
-	recipewidth = 0
-	for i in docare:
-		l = len(docare[i])
-		if l > recipewidth:
-			recipewidth = l # justification for printing out recipes.
-	recipewidth+=1
-
-	def __init__(self):
-		self.analyseonly = False
-		self.quiet = False
-		# defaults can use EPOCROOT
-		if "EPOCROOT" in os.environ:
-			self.epocroot = str(generic_path.Path(os.environ["EPOCROOT"]))
-		else:
-			self.epocroot = str(generic_path.Path('/'))
-		self.current_recipe_logged = False
-		self.cleaned = 0  # cleaned files
-		self.dotcount = 0 # progress dots printed so far
-		# list of strings to catch make errors (must be lowercase)
-		self.make_error_expr = set([
-				"error:",
-				": ***",
-				"make: interrupt/exception caught (code =",
-				"make.exe: interrupt/exception caught (code ="
-				])
-		# list of strings to catch make warnings (must be lowercase)
-		self.make_warning_expr = ["warning:"]
-
-		# list of strings to catch recipe warnings (must be lowercase)
-		self.recipe_warning_expr = ["warning:"]
-
-	def isMakeWarning(self, text):
-                """A simple test for warnings.
-                Can be extended do to more comprehensive checking."""
-		# generic warnings checked
-		# array of make_warning_expr holds all the possible values
-		for warn in self.make_warning_expr:
-			if warn in text.lower():
-				return True
-	
-		return False
-
-
-	def isMakeError(self, text):
-		"""A simple test for errors.	
-		Can be extended to do more comprehensive checking."""
-
-		# make, emake and pvmgmake spit out things like
-		# make: *** No rule to make target X, needed by Y. Stop.
-		#
-		# array of make_error_expr holds all the possible values
-		for err in self.make_error_expr:
-			if err in text.lower():
-				return True
-		
-		return False
-
-
-	def open(self, raptor_instance):
-		"""Set output to stdout for the various I/O methods to write to."""
-		self.raptor = raptor_instance
-
-		# Be totally silent?
-		if self.raptor.logFileName is None:
-			self.analyseonly = True
-
-		# Only print errors and warnings?
-		if self.raptor.quiet:
-			self.quiet = True
-		
-		# keep count of errors and warnings
-		self.err_count = 0
-		self.warn_count = 0
-		self.suppressed_warn_count = 0
-		self.inBody = False
-		self.inRecipe = False
-		return True
-		
-	def write(self, text):
-		"""Write errors and warnings to stdout"""
-		
-		if text.startswith("<error"):
-			start = text.find(">")
-			end = text.rfind("<")
-			self.err_count += 1
-			if not self.analyseonly:
-				sys.stderr.write(str(raptor.name) + ": error: %s\n" \
-						% text[(start + 1):end])
-		elif text.startswith("<warning"):
-			start = text.find(">")
-			end = text.rfind("<")
-			self.warn_count += 1
-			if not self.analyseonly:
-				sys.stdout.write(str(raptor.name) + ": warning: %s\n" \
-					% text[(start + 1):end])
-		elif text.startswith("<status "):
-			# detect the status report from a recipe
-			if text.find('failed') != -1:
-				self.failed = True
-			else:
-				self.failed = False
-			return
-		elif text.startswith("<recipe "):
-			# detect the start of a recipe
-			if self.inRecipe:
-				sys.stdout.flush()
-				sys.stderr.write(self.formatError("Opening recipe tag found " \
-						+ "before closing recipe tag for previous recipe:\n" \
-						+ "Discarding previous recipe (Possible logfile " \
-						+ "corruption)"))
-				sys.stderr.flush()
-			self.inRecipe = True
-			self.current_recipe_logged = False
-			m = FilterTerminal.attribute_re.findall(text)
-			self.recipe_dict = dict ()
-			for i in m:
-				self.recipe_dict[i[0]] = i[1]
-
-			# Decide what to tell the user about this recipe
-			# The target file or the source file?  
-			name = None
-			if 'source' in self.recipe_dict:
-				name = self.recipe_dict['source']
-
-			name_to_user = ""
-			# Make source files relative to the current directory if they are 
-		 	# not generated files in epocroot.  Also make sure path is in 
-			# the appropriate format for the user's shell.
-			if name and (name.find("epoc32") == -1 or name.endswith('.UID.CPP')):
-				for i in name.rsplit():
-					name_to_user += " " + generic_path.Path(i).From(generic_path.CurrentDir()).GetShellPath()
-			else:
-				# using the target.  Shorten it if it's in epocroot by just chopping off
-				# epocroot
-				name_to_user = self.recipe_dict['target']
-				if name_to_user.find(self.epocroot) != -1:
-					name_to_user = name_to_user.replace(self.epocroot,"")
-					if name_to_user.startswith('/') or name_to_user.startswith('\\'):
-						name_to_user = name_to_user[1:]
-				name_to_user = generic_path.Path(name_to_user).GetShellPath()	
-			self.recipe_dict['name_to_user'] = name_to_user
-			self.recipe_dict['mappedname'] = self.recipe_dict['name'] 
-
-			# Status message to indicate that we are building
-			recipename = self.recipe_dict['name']
-			if recipename in FilterTerminal.docare:
-				self.recipe_dict['mappedname'] = FilterTerminal.docare[recipename]
-				self.logit_if()
-
-			# This variable holds all recipe information
-			self.failed = False # Recipe status
-			self.recipeBody = []
-			return		
-		elif text.startswith("</recipe>"):
-			# detect the end of a recipe
-			if not self.inRecipe:
-				sys.stdout.flush()
-				sys.stderr.write(self.formatError("Closing recipe tag found " \
-						+ "before opening recipe tag:\nUnable to print " \
-						+ "recipe data (Possible logfile corruption)"))
-				sys.stderr.flush()
-			else:
-				self.inRecipe = False
-				
-				if self.failed == True:
-					if not self.analyseonly:
-						sys.stderr.write("\n FAILED %s for %s: %s\n" % \
-								(self.recipe_dict['name'],
-								self.recipe_dict['config'],
-								self.recipe_dict['name_to_user']))
-	
-						mmppath = generic_path.Path(self.recipe_dict['mmp']).From(generic_path.CurrentDir()).GetShellPath()
-						sys.stderr.write("  mmp: %s\n" % mmppath)
-						for L in self.recipeBody:
-							if not L.startswith('+'):
-								sys.stdout.write("   %s\n" % L.rstrip())
-					self.err_count += 1
-				else:
-					r = Recipe.factory(self.recipe_dict['name'], "".join(self.recipeBody))
-					warnings = r.warnings()
-					info = r.info()
-					if len(warnings) > 0:
-						if not self.analyseonly:
-							for L in self.recipeBody:
-								if not L.startswith('+'):
-									sys.stdout.write("   %s\n" % L.rstrip())
-						self.warn_count += len(warnings)
-	
-				self.recipeBody = []
-			return
-		elif not self.inRecipe and self.isMakeError(text):
-			# these two statements pick up errors coming from make
-			self.err_count += 1
-			sys.stderr.write("    %s\n" % text.rstrip())
-			return
-		elif not self.inRecipe and self.isMakeWarning(text):
-			self.warn_count += 1
-			sys.stdout.write("    %s\n" % text.rstrip())
-			return
-		elif text.startswith("<![CDATA["):
-                	# save CDATA body during a recipe
-			if self.inRecipe:
-				self.inBody = True
-		elif text.startswith("]]>"):
-			if self.inRecipe:
-				self.inBody = False
-		elif text.startswith("<info>Copied"):
-			if not self.analyseonly and not self.quiet:
-				start = text.find(" to ") + 4
-				end = text.find("</info>",start)
-				short_target = text[start:end]
-				if short_target.startswith(self.epocroot):
-					short_target = short_target.replace(self.epocroot,"")[1:]
-				short_target = generic_path.Path(short_target).GetShellPath()
-				sys.stdout.write(" %s: %s\n" % ("export".ljust(FilterTerminal.recipewidth), short_target))
-			return
-		elif text.find("<rm files") != -1 or text.find("<rmdir ") != -1:
-			# search for cleaning output but only if we 
-			# are not in some recipe (that would be pointless)
-			if not self.analyseonly and not self.quiet:
-				if  self.cleaned == 0:
-					sys.stdout.write("\ncleaning ")
-					self.cleaned+=1
-				elif self.dotcount < FilterTerminal.maxdots:
-					if self.cleaned % 5 == 0:
-						self.dotcount+=1
-						sys.stdout.write(".")
-					self.cleaned+=1
-			
-				return
-		elif self.inBody:
-			# We are parsing the output from a recipe
-			# we have to keep the output until we find out
-			# if the recipe failed. But not all of it if it turns
-			# out to be very long
-			if len(self.recipeBody) < FilterTerminal.recipelinelimit:
-				self.recipeBody.append(text)
-
-	def logit(self):
-		""" log a message """
-		info = self.recipe_dict['mappedname'].ljust(FilterTerminal.recipewidth)
-		config = self.recipe_dict['config']
-		name = self.recipe_dict['name_to_user'].lstrip()
-		# If its a multifile config, we print source files one below the other in a single
-		# 'compile:' statement
-		if config.endswith('multifile'):
-			files =  self.recipe_dict['name_to_user'].split()
-			name = ""
-			for i in files:
-				if i == files[0]:
-					name +=  i
-				else:
-					name +=  '\n\t      ' + i
-		sys.stdout.write(" %s: %s  \t[%s]\n" % (info, name, config))
-
-	def logit_if(self):
-		""" Tell the user about the recipe that we are processing """
-		if not self.analyseonly and not self.quiet:
-			if self.inRecipe and not self.current_recipe_logged:
-				self.logit()
-				self.current_recipe_logged = True
-	
-	def summary(self):
-		"""Errors and warnings summary"""
-		
-		if self.raptor.skipAll or self.analyseonly:
-			return
-
-
-		if self.cleaned != 0:
-			sys.stdout.write("\n\n")
-
-		if self.warn_count > 0 or self.err_count > 0:
-			sys.stdout.write("\n%s : warnings: %s\n" % (raptor.name,
-					self.warn_count))
-			sys.stdout.write("%s : errors: %s\n" % (raptor.name,
-					self.err_count))
-		else:
-			sys.stdout.write("\nno warnings or errors\n")
-
-		sys.stdout.write("\nRun time %d seconds\n" % self.raptor.runtime);
-		sys.stdout.write("\n")
-		return True
-	
-	def close(self):
-		"""Tell raptor that there were errors."""
-		if self.err_count > 0:
-			return False
-		return True
-
+#
+# Copyright (c) 2008-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: 
+# Filter class for filtering XML logs and generating reports
+# Prints errors and warnings to stdout
+#
+
+import sys
+import raptor
+import filter_interface
+import generic_path
+import os
+import os.path
+import re
+
+class Recipe(object):
+	"""State machine that parses a recipe
+	"""
+
+	suppress = []
+	warningRE = re.compile("^.*((Warning:)|(MAKEDEF WARNING:)) .*$", re.DOTALL | re.M | re.I)
+	infoRE = None
+	name = [ "default" ]
+	recipes = []
+
+	def __init__(self, text):
+		self.suppress = self.__class__.suppress
+		self.text = text
+		self.warningRE = Recipe.warningRE
+	
+	def warnings(self):
+		return self.warningRE.findall(self.text)
+
+	def info(self):
+		if self.infoRE:
+			return self.infoRE.findall(self.text)
+		else:
+			return []
+
+	@classmethod			
+	def factory(cls, name, text):
+		for r in Recipe.recipes:
+			if name in r.name:
+				return r(text)
+		return Recipe(text)
+	
+
+class MwLinkerRecipe(Recipe):
+	suppress = [ 
+		re.compile(
+r"^mwldsym2: warning: Cannot locate library \"MSL_All_Static_MSE_Symbian\" specified in #pragma comment\(lib,...\)$"
+r"[\n\r]*mwldsym2: warning: referenced from.*$"
+r"[\n\r]*mwldsym2: warning: Option 'Use default libraries' is enabled but linker used.*$"
+r"[\n\r]*mwldsym2: warning: runtime library from MW\[...\]LibraryFiles \(msl_all_static_mse_symbian_d.lib\);$"
+r"[\n\r]*mwldsym2: warning: this indicates a potential settings/libraries mismatch.*$"
+		, re.M)
+		, re.compile(
+r"^mwldsym2.exe: warning: Multiply defined symbol: ___get_MSL_init_count in.*$"
+r"[\n\r]*mwldsym2.exe: warning: files uc_cwhelp.obj \(.*\), startup.win32.c.obj \(msl_all_static_mse_symbian_d.lib\),.*$"
+r"[\n\r]*mwldsym2.exe: warning: keeping definition in startup.win32.c.obj.*$"
+		, re.M )
+		, re.compile(
+r"^mwldsym2.exe: warning: Option 'Use default libraries' is enabled but linker used.*$"
+r"[\n\r]*mwldsym2.exe: warning: runtime library from MW\[...\]LibraryFiles \(msl_all_static_mse_symbian_d.lib\);.*$"
+r"[\n\r]*mwldsym2.exe: warning: this indicates a potential settings/libraries mismatch.*$"
+	, re.M)
+	]
+	name = [ "win32stagetwolink", "win32simplelink" ]
+
+	def warnings(self):
+		edited = self.text
+		for s in MwLinkerRecipe.suppress:
+			edited = s.sub("", edited)
+		return Recipe.warningRE.findall(edited)
+
+Recipe.recipes.append(MwLinkerRecipe)
+
+
+class FreezeRecipe(Recipe):
+	name = [ "freeze" ]
+	warningRE = re.compile("^(WARNING:) .*$", re.DOTALL | re.M | re.I)
+	infoRE = re.compile("^(EFREEZE:) .*$", re.DOTALL | re.M | re.I)
+
+	def __init__(self, text):
+		Recipe.__init__(self, text)
+		self.warningRE = FreezeRecipe.warningRE
+		self.infoRE = FreezeRecipe.infoRE
+
+Recipe.recipes.append(FreezeRecipe)
+
+
+
+class FilterTerminal(filter_interface.Filter):
+
+	attribute_re = re.compile("([a-z][a-z0-9]*)='([^']*)'",re.I)
+	maxdots = 40 # if one prints dots then don't print masses
+	recipelinelimit = 1024 # don't scan ultra-long recipes in case we run out of memory
+
+	# recipes that we think most users are interested in
+	# and the mapping that we will use to output them as
+	docare = {
+		"asmcompile" : "asmcompile" ,
+		"compile" : "compile" ,
+		"postlink" : "target",
+		"linkandpostlink" : "target",
+		"resourcecompile" : "resource",
+		"genstringtable" : "strtable",
+		"tem" : "tem",
+		"bitmapcompile" : "bitmap",
+		"bitmapcopy" : "bitmapcopy",
+		"win32compile2object" : "compile",
+		"win32stagetwolink" : "target",
+		"win32simplelink" : "target",
+		"tools2install" : "target",
+		"compile2object" : "compile",
+		"msvctoolsinstall" : "target",
+		"msvctoolscompile" : "compile",
+		"freeze" : "freeze",
+		"win32archive" : "target"
+	}
+
+	# Determine the width of the largest mapped recipe name
+	recipewidth = 0
+	for i in docare:
+		l = len(docare[i])
+		if l > recipewidth:
+			recipewidth = l # justification for printing out recipes.
+	recipewidth+=1
+
+	def __init__(self):
+		self.analyseonly = False
+		self.quiet = False
+		# defaults can use EPOCROOT
+		if "EPOCROOT" in os.environ:
+			self.epocroot = str(generic_path.Path(os.environ["EPOCROOT"]))
+		else:
+			self.epocroot = str(generic_path.Path('/'))
+		self.current_recipe_logged = False
+		self.cleaned = 0  # cleaned files
+		self.dotcount = 0 # progress dots printed so far
+		# list of strings to catch make errors (must be lowercase)
+		self.make_error_expr = set([
+				"error:",
+				": ***",
+				"make: interrupt/exception caught (code =",
+				"make.exe: interrupt/exception caught (code ="
+				])
+		# list of strings to catch make warnings (must be lowercase)
+		self.make_warning_expr = ["warning:"]
+
+		# list of strings to catch recipe warnings (must be lowercase)
+		self.recipe_warning_expr = ["warning:"]
+		
+	def isMakeWarning(self, text):
+                """A simple test for warnings.
+                Can be extended do to more comprehensive checking."""
+		# generic warnings checked
+		# array of make_warning_expr holds all the possible values
+		for warn in self.make_warning_expr:
+			if warn in text.lower():
+				return True
+	
+		return False
+
+
+	def isMakeError(self, text):
+		"""A simple test for errors.	
+		Can be extended to do more comprehensive checking."""
+
+		# make, emake and pvmgmake spit out things like
+		# make: *** No rule to make target X, needed by Y. Stop.
+		#
+		# array of make_error_expr holds all the possible values
+		for err in self.make_error_expr:
+			if err in text.lower():
+				return True
+		
+		return False
+
+
+	def open(self, raptor_instance):
+		"""Set output to stdout for the various I/O methods to write to."""
+		self.raptor = raptor_instance
+
+		# Be totally silent?
+		if self.raptor.logFileName is None:
+			self.analyseonly = True
+
+		# Only print errors and warnings?
+		if self.raptor.quiet:
+			self.quiet = True
+		
+		# the build configurations which were reported
+		self.built_configs = []
+		
+		# keep count of errors and warnings
+		self.err_count = 0
+		self.warn_count = 0
+		self.suppressed_warn_count = 0
+		self.inBody = False
+		self.inRecipe = False
+		return True
+		
+	def write(self, text):
+		"""Write errors and warnings to stdout"""
+		
+		if text.startswith("<error"):
+			start = text.find(">")
+			end = text.rfind("<")
+			self.err_count += 1
+			if not self.analyseonly:
+				sys.stderr.write(str(raptor.name) + ": error: %s\n" \
+						% text[(start + 1):end])
+		elif text.startswith("<warning"):
+			start = text.find(">")
+			end = text.rfind("<")
+			self.warn_count += 1
+			if not self.analyseonly:
+				sys.stdout.write(str(raptor.name) + ": warning: %s\n" \
+					% text[(start + 1):end])
+		elif text.startswith("<status "):
+			# detect the status report from a recipe
+			if text.find('failed') != -1:
+				self.failed = True
+				if text.find("reason='timeout'") != -1:
+					self.timedout = True
+			else:
+				self.failed = False
+			return
+		elif text.startswith("<recipe "):
+			# detect the start of a recipe
+			if self.inRecipe:
+				sys.stdout.flush()
+				sys.stderr.write(self.formatError("Opening recipe tag found " \
+						+ "before closing recipe tag for previous recipe:\n" \
+						+ "Discarding previous recipe (Possible logfile " \
+						+ "corruption)"))
+				sys.stderr.flush()
+			self.inRecipe = True
+			self.current_recipe_logged = False
+			m = FilterTerminal.attribute_re.findall(text)
+			self.recipe_dict = dict ()
+			for i in m:
+				self.recipe_dict[i[0]] = i[1]
+
+			# Decide what to tell the user about this recipe
+			# The target file or the source file?  
+			name = None
+			if 'source' in self.recipe_dict:
+				name = self.recipe_dict['source']
+
+			name_to_user = ""
+			# Make source files relative to the current directory if they are 
+		 	# not generated files in epocroot.  Also make sure path is in 
+			# the appropriate format for the user's shell.
+			if name and (name.find("epoc32") == -1 or name.endswith('.UID.CPP')):
+				for i in name.rsplit():
+					name_to_user += " " + generic_path.Path(i).From(generic_path.CurrentDir()).GetShellPath()
+			else:
+				# using the target.  Shorten it if it's in epocroot by just chopping off
+				# epocroot
+				name_to_user = self.recipe_dict['target']
+				if name_to_user.find(self.epocroot) != -1:
+					name_to_user = name_to_user.replace(self.epocroot,"")
+					if name_to_user.startswith('/') or name_to_user.startswith('\\'):
+						name_to_user = name_to_user[1:]
+				name_to_user = generic_path.Path(name_to_user).GetShellPath()	
+			self.recipe_dict['name_to_user'] = name_to_user
+			self.recipe_dict['mappedname'] = self.recipe_dict['name'] 
+
+			# Status message to indicate that we are building
+			recipename = self.recipe_dict['name']
+			if recipename in FilterTerminal.docare:
+				self.recipe_dict['mappedname'] = FilterTerminal.docare[recipename]
+				self.logit_if()
+
+			# This variable holds all recipe information
+			self.failed = False # Recipe status
+			self.timedout = False # Did it Timeout?
+			self.recipeBody = []
+			self.recipelineExceeded = 0
+			return		
+		elif text.startswith("</recipe>"):
+			# detect the end of a recipe
+			if not self.inRecipe:
+				sys.stdout.flush()
+				sys.stderr.write(self.formatError("Closing recipe tag found " \
+						+ "before opening recipe tag:\nUnable to print " \
+						+ "recipe data (Possible logfile corruption)"))
+				sys.stderr.flush()
+			else:
+				self.inRecipe = False
+				
+				if self.failed == True:
+					if not self.analyseonly:
+						reason=""
+						if self.timedout:
+							reason="(timeout)"
+
+						sys.stderr.write("\n FAILED %s %s for %s: %s\n" % \
+								(self.recipe_dict['name'],
+								reason,
+								self.recipe_dict['config'],
+								self.recipe_dict['name_to_user']))
+	
+						mmppath = generic_path.Path(self.recipe_dict['mmp']).From(generic_path.CurrentDir()).GetShellPath()
+						if mmppath is not "":
+							sys.stderr.write("  mmp: %s\n" % mmppath)
+						if self.timedout:
+							sys.stderr.write( \
+"""    Timeouts may be due to network related issues (e.g. license servers),
+    tool bugs or abnormally large components. TALON_TIMEOUT can be adjusted 
+    in the make engine configuration if required.  Make engines may have 
+    their own timeouts that Raptor cannot influence
+""")
+						else:
+							for L in self.recipeBody:
+								if not L.startswith('+'):
+									sys.stdout.write("   %s\n" % L.rstrip())
+					self.err_count += 1
+				else:
+					r = Recipe.factory(self.recipe_dict['name'], "".join(self.recipeBody))
+					warnings = r.warnings()
+					info = r.info()
+					if len(warnings) or len(info):
+						if not self.analyseonly:
+							for L in self.recipeBody:
+								if not L.startswith('+'):
+									sys.stdout.write("   %s\n" % L.rstrip())
+						self.warn_count += len(warnings)
+	
+				self.recipeBody = []
+			return
+		elif not self.inRecipe and self.isMakeError(text):
+			# these two statements pick up errors coming from make
+			self.err_count += 1
+			sys.stderr.write("    %s\n" % text.rstrip())
+			return
+		elif not self.inRecipe and self.isMakeWarning(text):
+			self.warn_count += 1
+			sys.stdout.write("    %s\n" % text.rstrip())
+			return
+		elif text.startswith("<![CDATA["):
+                	# save CDATA body during a recipe
+			if self.inRecipe:
+				self.inBody = True
+		elif text.startswith("]]>"):
+			if self.inRecipe:
+				self.inBody = False
+				if self.recipelineExceeded > 0:
+					self.recipeBody.append("[filter_terminal: OUTPUT TRUNCATED: " + \
+						"Recipe output limit exceeded; see logfile for full output " + \
+						"(%s lines shown out of %s)]" % (FilterTerminal.recipelinelimit, \
+						FilterTerminal.recipelinelimit + self.recipelineExceeded))
+		elif text.startswith("<info>Copied"):
+			if not self.analyseonly and not self.quiet:
+				start = text.find(" to ") + 4
+				end = text.find("</info>",start)
+				short_target = text[start:end]
+				if short_target.startswith(self.epocroot):
+					short_target = short_target.replace(self.epocroot,"")[1:]
+				short_target = generic_path.Path(short_target).GetShellPath()
+				sys.stdout.write(" %s: %s\n" % ("export".ljust(FilterTerminal.recipewidth), short_target))
+			return
+		elif text.find("<rm files") != -1 or text.find("<rmdir ") != -1:
+			# search for cleaning output but only if we 
+			# are not in some recipe (that would be pointless)
+			if not self.analyseonly and not self.quiet:
+				if  self.cleaned == 0:
+					sys.stdout.write("\ncleaning ")
+					self.cleaned+=1
+				elif self.dotcount < FilterTerminal.maxdots:
+					if self.cleaned % 5 == 0:
+						self.dotcount+=1
+						sys.stdout.write(".")
+					self.cleaned+=1
+			
+				return
+		elif self.inBody:
+			# We are parsing the output from a recipe
+			# we have to keep the output until we find out
+			# if the recipe failed. But not all of it if it turns
+			# out to be very long
+			if len(self.recipeBody) <= FilterTerminal.recipelinelimit:
+				self.recipeBody.append(text)
+			else:
+				self.recipelineExceeded += 1
+		elif text.startswith("<info>Buildable configuration '"):
+			# <info>Buildable configuration 'name'</info>
+			self.built_configs.append(text[30:-8])
+
+	def logit(self):
+		""" log a message """
+		info = self.recipe_dict['mappedname'].ljust(FilterTerminal.recipewidth)
+		config = self.recipe_dict['config']
+		name = self.recipe_dict['name_to_user'].lstrip()
+		# If its a multifile config, we print source files one below the other in a single
+		# 'compile:' statement
+		if config.endswith('multifile'):
+			files =  self.recipe_dict['name_to_user'].split()
+			name = ""
+			for i in files:
+				if i == files[0]:
+					name +=  i
+				else:
+					name +=  '\n\t      ' + i
+		sys.stdout.write(" %s: %s  \t[%s]\n" % (info, name, config))
+
+	def logit_if(self):
+		""" Tell the user about the recipe that we are processing """
+		if not self.analyseonly and not self.quiet:
+			if self.inRecipe and not self.current_recipe_logged:
+				self.logit()
+				self.current_recipe_logged = True
+	
+	def summary(self):
+		"""Errors and warnings summary"""
+		
+		if self.raptor.skipAll or self.analyseonly:
+			return
+
+
+		if self.cleaned != 0:
+			sys.stdout.write("\n\n")
+
+		if self.warn_count > 0 or self.err_count > 0:
+			sys.stdout.write("\n%s : warnings: %s\n" % (raptor.name,
+					self.warn_count))
+			sys.stdout.write("%s : errors: %s\n\n" % (raptor.name,
+					self.err_count))
+		else:
+			sys.stdout.write("\nno warnings or errors\n\n")
+
+		for bc in self.built_configs:
+			sys.stdout.write("built " + bc + "\n")
+			
+		sys.stdout.write("\nRun time %d seconds\n" % self.raptor.runtime);
+		sys.stdout.write("\n")
+		return True
+	
+	def close(self):
+		"""Tell raptor that there were errors."""
+		if self.err_count > 0:
+			return False
+		return True
+
--- a/sbsv2/raptor/python/plugins/filter_what.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/plugins/filter_what.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,128 +1,188 @@
-#
-# 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: 
-# Filter class for doing --what and --check operations
-#
-
-import os
-import sys
-import re
-import filter_interface
-
-class FilterWhat(filter_interface.Filter):
-
-	
-	def print_file(self, line, start, end):
-		"Ensure DOS slashes on Windows"
-		
-		"""Use chars between enclosing tags ("<>", "''", etc)
-				start = opening tag, so the line we need
-				actually starts at 'start + 1' """
-		if "win" in self.buildparameters.platform:
-			filename = line[(start + 1):end].replace("/","\\")
-		else:
-			filename = line[(start + 1):end]
-			
-		if self.check:
-			if not os.path.isfile(filename):
-				print "MISSING:", filename
-				self.ok = False
-		else:
-			self.outfile.write(filename+"\n")
-
-
-	def open(self, build_parameters):
-		"initialise"
-		
-		self.buildparameters = build_parameters
-		self.check = build_parameters.doCheck
-		self.what = build_parameters.doWhat
-
-		self.outfile = sys.stdout
-		self.outfile_close = False
-
-		if "FILTERWHAT_FILE" in os.environ:
-			try:
-				self.outfile = open(os.environ['FILTERWHAT_FILE'],"w+")
-				self.outfile_close = True
-			except Exception,e:
-				raise Exception("The 'What Filter' could not open the output file specified in the FILTER_WHAT environment variable: " + os.environ['FILTERWHAT_FILE'])
-		
-		# repetitions is for tracking repeated lines in the output log
-		# when --check and --what are called
-		self.repetitions = {}
-		
-		"Regex for old what output"
-		if "win" in self.buildparameters.platform:
-			self.regex = re.compile("^[a-zA-Z]:\S+$")
-		else:
-			self.regex = re.compile("^/\S+$")
-		
-		"Regex for targets"
-		self.target_regex = re.compile("^<(build|stringtable|resource|bitmap)>.*")
-			
-		"Regex for exports"
-		self.export_regex = re.compile("^<export destination.*")
-		
-		"Regex for zip exports"
-		self.zip_export_regex = re.compile("^<member>.*")
-		
-		self.ok = True		
-		return self.ok
-	
-	def write(self, text):
-		"process some log text"
-		
-		for line in text.splitlines():
-			line = line.rstrip()
-			
-			if not line in self.repetitions:
-				self.repetitions[line] = 0
-				
-			if self.repetitions[line] == 0:
-				if self.regex.match(line) and (self.what or self.check):
-					"Print the whole line"
-					self.print_file(line, (-1), len(line))
-					
-				if self.target_regex.match(line):
-					"Grab the filename between <build> and </build>" 
-					start = line.find(">")
-					end = line.rfind("<")
-					
-					self.print_file(line, start, end)
-					
-				elif self.export_regex.match(line):
-					"Grab the filename between the first set of '' chars" 
-					start = line.find("'")
-					end = line.find("'", (start + 1))
-					
-					self.print_file(line, start, end)
-						
-				elif self.zip_export_regex.match(line):
-					"Grab the filename between <member> and </member>" 
-					start = line.find(">")
-					end = line.rfind("<")
-					
-					self.print_file(line, start, end)
-						
-			self.repetitions[line] += 1
-				
-		return self.ok
-	
-	def close(self):
-		if self.outfile_close:
-			self.outfile.close()
-		return self.ok
-						
-	
+#
+# Copyright (c) 2008-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: 
+# Filter class for doing --what and --check operations
+#
+
+import os
+import sys
+import re
+import filter_interface
+
+class FilterWhat(filter_interface.Filter):
+
+	def __init__(self):
+		super(filter_interface.Filter,self).__init__()
+		self.path_prefix_to_strip = None
+		self.path_prefix_to_add_on = None
+		self.check = False
+	
+	def print_file(self, line, start, end):
+		"Ensure DOS slashes on Windows"
+		
+		"""Use chars between enclosing tags ("<>", "''", etc)
+				start = opening tag, so the line we need
+				actually starts at 'start + 1' """
+
+		abs_filename = line[(start + 1):end]
+		filename = abs_filename
+
+		# Adjust drive letters for case insensitivity on windows
+
+		path_prefix_to_strip = self.path_prefix_to_strip
+		if "win" in self.buildparameters.platform:
+			filename = filename[0].upper()+filename[1:]
+			filename = filename.replace("/","\\")
+
+		if path_prefix_to_strip:
+			if "win" in self.buildparameters.platform:
+				path_prefix_to_strip = path_prefix_to_strip[0].upper()+path_prefix_to_strip[1:].replace("/","\\")
+			if filename.startswith(path_prefix_to_strip):
+				filename = filename[len(path_prefix_to_strip):]
+			if self.path_prefix_to_add_on != None:
+				filename = self.path_prefix_to_add_on + filename
+			
+		if self.check:
+			if not os.path.isfile(abs_filename):
+				print "MISSING:", filename
+				self.ok = False
+		else:
+			self.outfile.write(filename+"\n")
+
+		self.prints += 1
+
+	def start_bldinf(self, bldinf):
+		pass
+
+	def end_bldinf(self):
+		pass
+		
+
+	def open(self, build_parameters):
+		"initialise"
+		
+
+		self.buildparameters = build_parameters
+		if build_parameters.doCheck:
+			self.check = True
+		self.what = build_parameters.doWhat
+
+		self.outfile = sys.stdout
+		self.outfile_close = False
+
+		if "FILTERWHAT_FILE" in os.environ:
+			try:
+				self.outfile = open(os.environ['FILTERWHAT_FILE'],"w+")
+				self.outfile_close = True
+			except Exception,e:
+				raise Exception("The 'What Filter' could not open the output file specified in the FILTER_WHAT environment variable: " + os.environ['FILTERWHAT_FILE'])
+		
+		# repetitions is for tracking repeated lines in the output log
+		# when --check and --what are called
+		self.repetitions = {}	
+		
+		"Regex for targets"
+		self.target_regex = re.compile("^<(build|stringtable|resource|bitmap)>.*")
+			
+		"Regex for exports"
+		self.export_regex = re.compile("^<export destination.*")
+		
+		"Regex for zip exports"
+		self.zip_export_regex = re.compile("^<member>.*")
+
+		"Regex for determining bld.inf name"
+		self.whatlog_regex = re.compile("^<whatlog *bldinf='(?P<bldinf>[^']*)'.*")
+		self.current_bldinf = ''
+		
+		self.prints = 0
+		self.ok = True		
+		return self.ok
+	
+	def write(self, text):
+		"process some log text"
+		
+		for line in text.splitlines():
+			line = line.rstrip()
+			
+			# we are normally the ONLY filter running so we have to pass on
+			# any errors and warnings that emerge
+			#
+			if line.startswith("<error"):
+				sys.stderr.write(self.formatError(line))
+				self.ok = False
+				continue
+			if line.startswith("<warning"):
+				sys.stderr.write(self.formatWarning(line))
+				continue
+				
+			if not line in self.repetitions:
+				self.repetitions[line] = 0
+				
+			if self.repetitions[line] == 0:
+					
+				if self.target_regex.match(line):
+					"Grab the filename between <build> and </build>" 
+					start = line.find(">")
+					end = line.rfind("<")
+					
+					self.print_file(line, start, end)
+					
+				elif self.export_regex.match(line):
+					"Grab the filename between the first set of '' chars" 
+					start = line.find("'")
+					end = line.find("'", (start + 1))
+					
+					self.print_file(line, start, end)
+						
+				elif self.zip_export_regex.match(line):
+					"Grab the filename between <member> and </member>" 
+					start = line.find(">")
+					end = line.rfind("<")
+					
+					self.print_file(line, start, end)
+
+			"work out what the 'current' bldinf file is"
+			m = self.whatlog_regex.match(line)
+			if m:
+				bi = m.groupdict()['bldinf']
+				if self.current_bldinf != bi:
+					if self.current_bldinf != '':
+						self.end_bldinf()
+					self.current_bldinf = bi
+					if bi != '':
+						self.start_bldinf(bi)
+							
+					
+						
+			self.repetitions[line] += 1
+				
+		return self.ok
+	
+	def summary(self):
+		if self.prints == 0:
+			if self.what:
+				message = "no WHAT information found"
+			else:
+				message = "no CHECK information found"
+				
+			sys.stderr.write(self.formatError(message))
+			self.ok = False
+		return self.ok
+		
+	def close(self):
+		if self.outfile_close:
+			self.outfile.close()
+		return self.ok
+						
+	
--- a/sbsv2/raptor/python/pyparsing.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/pyparsing.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,2961 +1,2961 @@
-# module pyparsing.py
-#
-# Copyright (c) 2003-2006  Paul T. McGuire
-#
-# Permission is hereby granted, free of charge, to any person obtaining
-# a copy of this software and associated documentation files (the
-# "Software"), to deal in the Software without restriction, including
-# without limitation the rights to use, copy, modify, merge, publish,
-# distribute, sublicense, and/or sell copies of the Software, and to
-# permit persons to whom the Software is furnished to do so, subject to
-# the following conditions:
-#
-# The above copyright notice and this permission notice shall be
-# included in all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-#
-#from __future__ import generators
-
-__doc__ = \
-"""
-pyparsing module - Classes and methods to define and execute parsing grammars
-
-The pyparsing module is an alternative approach to creating and executing simple grammars, 
-vs. the traditional lex/yacc approach, or the use of regular expressions.  With pyparsing, you
-don't need to learn a new syntax for defining grammars or matching expressions - the parsing module 
-provides a library of classes that you use to construct the grammar directly in Python.
-
-Here is a program to parse "Hello, World!" (or any greeting of the form "<salutation>, <addressee>!")::
-
-    from pyparsing import Word, alphas
-    
-    # define grammar of a greeting
-    greet = Word( alphas ) + "," + Word( alphas ) + "!" 
-    
-    hello = "Hello, World!"
-    print hello, "->", greet.parseString( hello )
-
-The program outputs the following::
-
-    Hello, World! -> ['Hello', ',', 'World', '!']
-
-The Python representation of the grammar is quite readable, owing to the self-explanatory 
-class names, and the use of '+', '|' and '^' operators.
-
-The parsed results returned from parseString() can be accessed as a nested list, a dictionary, or an 
-object with named attributes.
-
-The pyparsing module handles some of the problems that are typically vexing when writing text parsers:
- - extra or missing whitespace (the above program will also handle "Hello,World!", "Hello  ,  World  !", etc.)
- - quoted strings
- - embedded comments
-"""
-__version__ = "1.4.5"
-__versionTime__ = "16 December 2006 07:20"
-__author__ = "Paul McGuire <ptmcg@users.sourceforge.net>"
-
-import string
-import copy,sys
-import warnings
-import re
-import sre_constants
-import xml.sax.saxutils
-#~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) )
-
-def _ustr(obj):
-    """Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries
-       str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It
-       then < returns the unicode object | encodes it with the default encoding | ... >.
-    """
-    try:
-        # If this works, then _ustr(obj) has the same behaviour as str(obj), so
-        # it won't break any existing code.
-        return str(obj)
-        
-    except UnicodeEncodeError, e:
-        # The Python docs (http://docs.python.org/ref/customization.html#l2h-182)
-        # state that "The return value must be a string object". However, does a
-        # unicode object (being a subclass of basestring) count as a "string
-        # object"?
-        # If so, then return a unicode object:
-        return unicode(obj)
-        # Else encode it... but how? There are many choices... :)
-        # Replace unprintables with escape codes?
-        #return unicode(obj).encode(sys.getdefaultencoding(), 'backslashreplace_errors')
-        # Replace unprintables with question marks?
-        #return unicode(obj).encode(sys.getdefaultencoding(), 'replace')
-        # ...
-
-def _str2dict(strg):
-    return dict( [(c,0) for c in strg] )
-    #~ return set( [c for c in strg] )
-
-class _Constants(object):
-    pass
-    
-alphas     = string.lowercase + string.uppercase
-nums       = string.digits
-hexnums    = nums + "ABCDEFabcdef"
-alphanums  = alphas + nums    
-
-class ParseBaseException(Exception):
-    """base exception class for all parsing runtime exceptions"""
-    __slots__ = ( "loc","msg","pstr","parserElement" )
-    # Performance tuning: we construct a *lot* of these, so keep this
-    # constructor as small and fast as possible        
-    def __init__( self, pstr, loc, msg, elem=None ):
-        self.loc = loc
-        self.msg = msg
-        self.pstr = pstr
-        self.parserElement = elem
-
-    def __getattr__( self, aname ):
-        """supported attributes by name are:
-            - lineno - returns the line number of the exception text
-            - col - returns the column number of the exception text
-            - line - returns the line containing the exception text
-        """
-        if( aname == "lineno" ):
-            return lineno( self.loc, self.pstr )
-        elif( aname in ("col", "column") ):
-            return col( self.loc, self.pstr )
-        elif( aname == "line" ):
-            return line( self.loc, self.pstr )
-        else:
-            raise AttributeError, aname
-
-    def __str__( self ):
-        return "%s (at char %d), (line:%d, col:%d)" % ( self.msg, self.loc, self.lineno, self.column )
-    def __repr__( self ):
-        return _ustr(self)
-    def markInputline( self, markerString = ">!<" ):
-        """Extracts the exception line from the input string, and marks 
-           the location of the exception with a special symbol.
-        """
-        line_str = self.line
-        line_column = self.column - 1
-        if markerString:
-            line_str = "".join( [line_str[:line_column], markerString, line_str[line_column:]])
-        return line_str.strip()
-
-class ParseException(ParseBaseException):
-    """exception thrown when parse expressions don't match class"""
-    """supported attributes by name are:
-        - lineno - returns the line number of the exception text
-        - col - returns the column number of the exception text
-        - line - returns the line containing the exception text
-    """
-    pass
-    
-class ParseFatalException(ParseBaseException):
-    """user-throwable exception thrown when inconsistent parse content
-       is found; stops all parsing immediately"""
-    pass
-
-class ReparseException(ParseBaseException):
-    def __init_( self, newstring, restartLoc ):
-        self.newParseText = newstring
-        self.reparseLoc = restartLoc
-
-
-class RecursiveGrammarException(Exception):
-    """exception thrown by validate() if the grammar could be improperly recursive"""
-    def __init__( self, parseElementList ):
-        self.parseElementTrace = parseElementList
-    
-    def __str__( self ):
-        return "RecursiveGrammarException: %s" % self.parseElementTrace
-
-class ParseResults(object):
-    """Structured parse results, to provide multiple means of access to the parsed data:
-       - as a list (len(results))
-       - by list index (results[0], results[1], etc.)
-       - by attribute (results.<resultsName>)
-       """
-    __slots__ = ( "__toklist", "__tokdict", "__doinit", "__name", "__parent", "__accumNames" )
-    def __new__(cls, toklist, name=None, asList=True, modal=True ):
-        if isinstance(toklist, cls):
-            return toklist
-        retobj = object.__new__(cls)
-        retobj.__doinit = True
-        return retobj
-        
-    # Performance tuning: we construct a *lot* of these, so keep this
-    # constructor as small and fast as possible
-    def __init__( self, toklist, name=None, asList=True, modal=True ):
-        if self.__doinit:
-            self.__doinit = False
-            self.__name = None
-            self.__parent = None
-            self.__accumNames = {}
-            if isinstance(toklist, list):
-                self.__toklist = toklist[:]
-            else:
-                self.__toklist = [toklist]
-            self.__tokdict = dict()
-
-        # this line is related to debugging the asXML bug
-        #~ asList = False
-        
-        if name:
-            if not modal:
-                self.__accumNames[name] = 0
-            if isinstance(name,int):
-                name = _ustr(name) # will always return a str, but use _ustr for consistency
-            self.__name = name
-            if not toklist in (None,'',[]):
-                if isinstance(toklist,basestring): 
-                    toklist = [ toklist ]
-                if asList:
-                    if isinstance(toklist,ParseResults):
-                        self[name] = (toklist.copy(),-1)
-                    else:
-                        self[name] = (ParseResults(toklist[0]),-1)
-                    self[name].__name = name
-                else:
-                    try:
-                        self[name] = toklist[0]
-                    except (KeyError,TypeError):
-                        self[name] = toklist
-
-    def __getitem__( self, i ):
-        if isinstance( i, (int,slice) ):
-            return self.__toklist[i]
-        else:
-            if i not in self.__accumNames:
-                return self.__tokdict[i][-1][0]
-            else:
-                return ParseResults([ v[0] for v in self.__tokdict[i] ])
-
-    def __setitem__( self, k, v ):
-        if isinstance(v,tuple):
-            self.__tokdict[k] = self.__tokdict.get(k,list()) + [v]
-            sub = v[0]
-        elif isinstance(k,int):
-            self.__toklist[k] = v
-            sub = v
-        else:
-            self.__tokdict[k] = self.__tokdict.get(k,list()) + [(v,0)]
-            sub = v
-        if isinstance(sub,ParseResults):
-            sub.__parent = self
-        
-    def __delitem__( self, i ):
-        if isinstance(i,(int,slice)):
-            del self.__toklist[i]
-        else:
-            del self._tokdict[i]
-
-    def __contains__( self, k ):
-        return self.__tokdict.has_key(k)
-        
-    def __len__( self ): return len( self.__toklist )
-    def __nonzero__( self ): return len( self.__toklist ) > 0
-    def __iter__( self ): return iter( self.__toklist )
-    def keys( self ): 
-        """Returns all named result keys."""
-        return self.__tokdict.keys()
-    
-    def items( self ): 
-        """Returns all named result keys and values as a list of tuples."""
-        return [(k,self[k]) for k in self.__tokdict.keys()]
-    
-    def values( self ): 
-        """Returns all named result values."""
-        return [ v[-1][0] for v in self.__tokdict.values() ]
-
-    def __getattr__( self, name ):
-        if name not in self.__slots__:
-            if self.__tokdict.has_key( name ):
-                if name not in self.__accumNames:
-                    return self.__tokdict[name][-1][0]
-                else:
-                    return ParseResults([ v[0] for v in self.__tokdict[name] ])
-            else:
-                return ""
-        return None
-
-    def __add__( self, other ):
-        ret = self.copy()
-        ret += other
-        return ret
-        
-    def __iadd__( self, other ):
-        if other.__tokdict:
-            offset = len(self.__toklist)
-            addoffset = ( lambda a: (a<0 and offset) or (a+offset) )
-            otheritems = other.__tokdict.items()
-            otherdictitems = [(k,(v[0],addoffset(v[1])) ) for (k,vlist) in otheritems for v in vlist]
-            for k,v in otherdictitems:
-                self[k] = v
-                if isinstance(v[0],ParseResults):
-                    v[0].__parent = self
-        self.__toklist += other.__toklist
-        self.__accumNames.update( other.__accumNames )
-        del other
-        return self
-       
-    def __repr__( self ):
-        return "(%s, %s)" % ( repr( self.__toklist ), repr( self.__tokdict ) )
-
-    def __str__( self ):
-        out = "["
-        sep = ""
-        for i in self.__toklist:
-            if isinstance(i, ParseResults):
-                out += sep + _ustr(i)
-            else:
-                out += sep + repr(i)
-            sep = ", "
-        out += "]"
-        return out
-
-    def _asStringList( self, sep='' ):
-        out = []
-        for item in self.__toklist:
-            if out and sep:
-                out.append(sep)
-            if isinstance( item, ParseResults ):
-                out += item._asStringList()
-            else:
-                out.append( _ustr(item) )
-        return out
-
-    def asList( self ):
-        """Returns the parse results as a nested list of matching tokens, all converted to strings."""
-        out = []
-        for res in self.__toklist:
-            if isinstance(res,ParseResults):
-                out.append( res.asList() )
-            else:
-                out.append( res )
-        return out
-
-    def asDict( self ):
-        """Returns the named parse results as dictionary."""
-        return dict( self.items() )
-
-    def copy( self ):
-        """Returns a new copy of a ParseResults object."""
-        ret = ParseResults( self.__toklist )
-        ret.__tokdict = self.__tokdict.copy()
-        ret.__parent = self.__parent
-        ret.__accumNames.update( self.__accumNames )
-        ret.__name = self.__name
-        return ret
-        
-    def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
-        """Returns the parse results as XML. Tags are created for tokens and lists that have defined results names."""
-        nl = "\n"
-        out = []
-        namedItems = dict( [ (v[1],k) for (k,vlist) in self.__tokdict.items() for v in vlist ] )
-        nextLevelIndent = indent + "  "
-        
-        # collapse out indents if formatting is not desired
-        if not formatted:
-            indent = ""
-            nextLevelIndent = ""
-            nl = ""
-            
-        selfTag = None
-        if doctag is not None:
-            selfTag = doctag
-        else:
-            if self.__name:
-                selfTag = self.__name
-        
-        if not selfTag:
-            if namedItemsOnly:
-                return ""
-            else:
-                selfTag = "ITEM"
-        
-        out += [ nl, indent, "<", selfTag, ">" ]
-        
-        worklist = self.__toklist
-        for i,res in enumerate(worklist):
-            if isinstance(res,ParseResults):
-                if i in namedItems:
-                    out += [ res.asXML(namedItems[i], namedItemsOnly and doctag is None, nextLevelIndent,formatted)]
-                else:
-                    out += [ res.asXML(None, namedItemsOnly and doctag is None, nextLevelIndent,formatted)]
-            else:
-                # individual token, see if there is a name for it
-                resTag = None
-                if i in namedItems:
-                    resTag = namedItems[i]
-                if not resTag:
-                    if namedItemsOnly:
-                        continue
-                    else:
-                        resTag = "ITEM"
-                xmlBodyText = xml.sax.saxutils.escape(_ustr(res))
-                out += [ nl, nextLevelIndent, "<", resTag, ">", xmlBodyText, "</", resTag, ">" ]
-        
-        out += [ nl, indent, "</", selfTag, ">" ]
-        return "".join(out)
-
-    def __lookup(self,sub):
-        for k,vlist in self.__tokdict.items():
-            for v,loc in vlist:
-                if sub is v:
-                    return k
-        return None
-            
-    def getName(self):
-        """Returns the results name for this token expression."""
-        if self.__name:
-            return self.__name
-        elif self.__parent:
-            par = self.__parent
-            if par:
-                return par.__lookup(self)
-            else:
-                return None
-        elif (len(self) == 1 and 
-               len(self.__tokdict) == 1 and
-               self.__tokdict.values()[0][0][1] in (0,-1)):
-            return self.__tokdict.keys()[0]
-        else:
-            return None
-            
-    def dump(self,indent='',depth=0):
-        """Diagnostic method for listing out the contents of a ParseResults.
-           Accepts an optional indent argument so that this string can be embedded
-           in a nested display of other data."""
-        out = []
-        out.append( indent+str(self.asList()) )
-        keys = self.items()
-        keys.sort()
-        for k,v in keys:
-            if out:
-                out.append('\n')
-            out.append( "%s%s- %s: " % (indent,('  '*depth), k) )
-            if isinstance(v,ParseResults):
-                if v.keys():
-                    #~ out.append('\n')
-                    out.append( v.dump(indent,depth+1) )
-                    #~ out.append('\n')
-                else:
-                    out.append(str(v))
-            else:
-                out.append(str(v))
-        #~ out.append('\n')
-        return "".join(out)
-
-    # add support for pickle protocol
-    def __getstate__(self):
-        return ( self.__toklist,
-                 ( self.__tokdict.copy(),
-                   self.__parent,
-                   self.__accumNames,
-                   self.__name ) )
-    
-    def __setstate__(self,state):
-        self.__toklist = state[0]
-        self.__tokdict, \
-        self.__parent, \
-        inAccumNames, \
-        self.__name = state[1]
-        self.__accumNames = {}
-        self.__accumNames.update(inAccumNames)
-
-
-def col (loc,strg):
-    """Returns current column within a string, counting newlines as line separators.
-   The first column is number 1.
-   """
-    return (loc<len(strg) and strg[loc] == '\n') and 1 or loc - strg.rfind("\n", 0, loc)
-
-def lineno(loc,strg):
-    """Returns current line number within a string, counting newlines as line separators.
-   The first line is number 1.
-   """
-    return strg.count("\n",0,loc) + 1
-
-def line( loc, strg ):
-    """Returns the line of text containing loc within a string, counting newlines as line separators.
-       """
-    lastCR = strg.rfind("\n", 0, loc)
-    nextCR = strg.find("\n", loc)
-    if nextCR > 0:
-        return strg[lastCR+1:nextCR]
-    else:
-        return strg[lastCR+1:]
-
-def _defaultStartDebugAction( instring, loc, expr ):
-    print "Match",expr,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )
-
-def _defaultSuccessDebugAction( instring, startloc, endloc, expr, toks ):
-    print "Matched",expr,"->",toks.asList()
-    
-def _defaultExceptionDebugAction( instring, loc, expr, exc ):
-    print "Exception raised:", exc
-
-def nullDebugAction(*args):
-    """'Do-nothing' debug action, to suppress debugging output during parsing."""
-    pass
-
-class ParserElement(object):
-    """Abstract base level parser element class."""
-    DEFAULT_WHITE_CHARS = " \n\t\r"
-    
-    def setDefaultWhitespaceChars( chars ):
-        """Overrides the default whitespace chars
-        """
-        ParserElement.DEFAULT_WHITE_CHARS = chars
-    setDefaultWhitespaceChars = staticmethod(setDefaultWhitespaceChars)
-    
-    def __init__( self, savelist=False ):
-        self.parseAction = list()
-        self.failAction = None
-        #~ self.name = "<unknown>"  # don't define self.name, let subclasses try/except upcall
-        self.strRepr = None
-        self.resultsName = None
-        self.saveAsList = savelist
-        self.skipWhitespace = True
-        self.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
-        self.copyDefaultWhiteChars = True
-        self.mayReturnEmpty = False
-        self.keepTabs = False
-        self.ignoreExprs = list()
-        self.debug = False
-        self.streamlined = False
-        self.mayIndexError = True
-        self.errmsg = ""
-        self.modalResults = True
-        self.debugActions = ( None, None, None )
-        self.re = None
-
-    def copy( self ):
-        """Make a copy of this ParserElement.  Useful for defining different parse actions
-           for the same parsing pattern, using copies of the original parse element."""
-        cpy = copy.copy( self )
-        cpy.parseAction = self.parseAction[:]
-        cpy.ignoreExprs = self.ignoreExprs[:]
-        if self.copyDefaultWhiteChars:
-            cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
-        return cpy
-
-    def setName( self, name ):
-        """Define name for this expression, for use in debugging."""
-        self.name = name
-        self.errmsg = "Expected " + self.name
-        return self
-
-    def setResultsName( self, name, listAllMatches=False ):
-        """Define name for referencing matching tokens as a nested attribute 
-           of the returned parse results.
-           NOTE: this returns a *copy* of the original ParserElement object;
-           this is so that the client can define a basic element, such as an
-           integer, and reference it in multiple places with different names.
-        """
-        newself = self.copy()
-        newself.resultsName = name
-        newself.modalResults = not listAllMatches
-        return newself
-
-    def normalizeParseActionArgs( f ):
-        """Internal method used to decorate parse actions that take fewer than 3 arguments,
-           so that all parse actions can be called as f(s,l,t)."""
-        STAR_ARGS = 4
-
-        try:
-            restore = None
-            if isinstance(f,type):
-                restore = f
-                f = f.__init__
-            if f.func_code.co_flags & STAR_ARGS:
-                return f
-            numargs = f.func_code.co_argcount
-            if hasattr(f,"im_self"):
-                numargs -= 1
-            if restore:
-                f = restore
-        except AttributeError:
-            try:
-                # not a function, must be a callable object, get info from the
-                # im_func binding of its bound __call__ method
-                if f.__call__.im_func.func_code.co_flags & STAR_ARGS:
-                    return f
-                numargs = f.__call__.im_func.func_code.co_argcount
-                if hasattr(f.__call__,"im_self"):
-                    numargs -= 1
-            except AttributeError:
-                # not a bound method, get info directly from __call__ method
-                if f.__call__.func_code.co_flags & STAR_ARGS:
-                    return f
-                numargs = f.__call__.func_code.co_argcount
-                if hasattr(f.__call__,"im_self"):
-                    numargs -= 1
-
-        #~ print "adding function %s with %d args" % (f.func_name,numargs)
-        if numargs == 3:
-            return f
-        else:
-            if numargs == 2:
-                def tmp(s,l,t):
-                    return f(l,t)
-            elif numargs == 1:
-                def tmp(s,l,t):
-                    return f(t)
-            else: #~ numargs == 0:
-                def tmp(s,l,t):
-                    return f()
-            return tmp
-    normalizeParseActionArgs = staticmethod(normalizeParseActionArgs)
-            
-    def setParseAction( self, *fns ):
-        """Define action to perform when successfully matching parse element definition.
-           Parse action fn is a callable method with 0-3 arguments, called as fn(s,loc,toks),
-           fn(loc,toks), fn(toks), or just fn(), where:
-            - s   = the original string being parsed
-            - loc = the location of the matching substring
-            - toks = a list of the matched tokens, packaged as a ParseResults object
-           If the functions in fns modify the tokens, they can return them as the return
-           value from fn, and the modified list of tokens will replace the original.
-           Otherwise, fn does not need to return any value."""
-        self.parseAction = map(self.normalizeParseActionArgs, list(fns))
-        return self
-
-    def addParseAction( self, *fns ):
-        """Add parse action to expression's list of parse actions. See setParseAction_."""
-        self.parseAction += map(self.normalizeParseActionArgs, list(fns))
-        return self
-
-    def setFailAction( self, fn ):
-        """Define action to perform if parsing fails at this expression. 
-           Fail acton fn is a callable function that takes the arguments 
-           fn(s,loc,expr,err) where:
-            - s = string being parsed
-            - loc = location where expression match was attempted and failed
-            - expr = the parse expression that failed
-            - err = the exception thrown
-           The function returns no value.  It may throw ParseFatalException
-           if it is desired to stop parsing immediately."""
-        self.failAction = fn
-        return self
-        
-    def skipIgnorables( self, instring, loc ):
-        exprsFound = True
-        while exprsFound:
-            exprsFound = False
-            for e in self.ignoreExprs:
-                try:
-                    while 1:
-                        loc,dummy = e._parse( instring, loc )
-                        exprsFound = True
-                except ParseException:
-                    pass
-        return loc
-
-    def preParse( self, instring, loc ):
-        if self.ignoreExprs:
-            loc = self.skipIgnorables( instring, loc )
-        
-        if self.skipWhitespace:
-            wt = self.whiteChars
-            instrlen = len(instring)
-            while loc < instrlen and instring[loc] in wt:
-                loc += 1
-                
-        return loc
-
-    def parseImpl( self, instring, loc, doActions=True ):
-        return loc, []
-
-    def postParse( self, instring, loc, tokenlist ):
-        return tokenlist
-
-    #~ @profile
-    def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ):
-        debugging = ( self.debug ) #and doActions )
-
-        if debugging or self.failAction:
-            #~ print "Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )
-            if (self.debugActions[0] ):
-                self.debugActions[0]( instring, loc, self )
-            if callPreParse:
-                preloc = self.preParse( instring, loc )
-            else:
-                preloc = loc
-            tokensStart = loc
-            try:
-                try:
-                    loc,tokens = self.parseImpl( instring, preloc, doActions )
-                except IndexError:
-                    raise ParseException( instring, len(instring), self.errmsg, self )
-            #~ except ReparseException, retryEx:
-                #~ pass
-            except ParseException, err:
-                #~ print "Exception raised:", err
-                if self.debugActions[2]:
-                    self.debugActions[2]( instring, tokensStart, self, err )
-                if self.failAction:
-                    self.failAction( instring, tokensStart, self, err )
-                raise
-        else:
-            if callPreParse:
-                preloc = self.preParse( instring, loc )
-            else:
-                preloc = loc
-            tokensStart = loc
-            if self.mayIndexError or loc >= len(instring):
-                try:
-                    loc,tokens = self.parseImpl( instring, preloc, doActions )
-                except IndexError:
-                    raise ParseException( instring, len(instring), self.errmsg, self )
-            else:
-                loc,tokens = self.parseImpl( instring, preloc, doActions )
-        
-        tokens = self.postParse( instring, loc, tokens )
-
-        retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults )
-        if self.parseAction and doActions:
-            if debugging:
-                try:
-                    for fn in self.parseAction:
-                        tokens = fn( instring, tokensStart, retTokens )
-                        if tokens is not None:
-                            retTokens = ParseResults( tokens, 
-                                                      self.resultsName, 
-                                                      asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), 
-                                                      modal=self.modalResults )
-                except ParseException, err:
-                    #~ print "Exception raised in user parse action:", err
-                    if (self.debugActions[2] ):
-                        self.debugActions[2]( instring, tokensStart, self, err )
-                    raise
-            else:
-                for fn in self.parseAction:
-                    tokens = fn( instring, tokensStart, retTokens )
-                    if tokens is not None:
-                        retTokens = ParseResults( tokens, 
-                                                  self.resultsName, 
-                                                  asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), 
-                                                  modal=self.modalResults )
-
-        if debugging:
-            #~ print "Matched",self,"->",retTokens.asList()
-            if (self.debugActions[1] ):
-                self.debugActions[1]( instring, tokensStart, loc, self, retTokens )
-
-        return loc, retTokens
-
-    def tryParse( self, instring, loc ):
-        return self._parse( instring, loc, doActions=False )[0]
-    
-    # this method gets repeatedly called during backtracking with the same arguments -
-    # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression
-    def _parseCache( self, instring, loc, doActions=True, callPreParse=True ):
-        if doActions and self.parseAction:
-            return self._parseNoCache( instring, loc, doActions, callPreParse )
-        lookup = (self,instring,loc,callPreParse)
-        if lookup in ParserElement._exprArgCache:
-            value = ParserElement._exprArgCache[ lookup ]
-            if isinstance(value,Exception):
-                if isinstance(value,ParseBaseException):
-                    value.loc = loc
-                raise value
-            return value
-        else:
-            try:
-                ParserElement._exprArgCache[ lookup ] = \
-                    value = self._parseNoCache( instring, loc, doActions, callPreParse )
-                return value
-            except ParseBaseException, pe:
-                ParserElement._exprArgCache[ lookup ] = pe
-                raise
-
-    _parse = _parseNoCache
-
-    # argument cache for optimizing repeated calls when backtracking through recursive expressions
-    _exprArgCache = {}
-    def resetCache():
-        ParserElement._exprArgCache.clear()
-    resetCache = staticmethod(resetCache)
-    
-    _packratEnabled = False
-    def enablePackrat():
-        """Enables "packrat" parsing, which adds memoizing to the parsing logic.
-           Repeated parse attempts at the same string location (which happens 
-           often in many complex grammars) can immediately return a cached value, 
-           instead of re-executing parsing/validating code.  Memoizing is done of
-           both valid results and parsing exceptions.
-            
-           This speedup may break existing programs that use parse actions that 
-           have side-effects.  For this reason, packrat parsing is disabled when
-           you first import pyparsing.  To activate the packrat feature, your
-           program must call the class method ParserElement.enablePackrat().  If
-           your program uses psyco to "compile as you go", you must call 
-           enablePackrat before calling psyco.full().  If you do not do this,
-           Python will crash.  For best results, call enablePackrat() immediately
-           after importing pyparsing.
-        """
-        if not ParserElement._packratEnabled:
-            ParserElement._packratEnabled = True
-            ParserElement._parse = ParserElement._parseCache
-    enablePackrat = staticmethod(enablePackrat)
-
-    def parseString( self, instring ):
-        """Execute the parse expression with the given string.
-           This is the main interface to the client code, once the complete 
-           expression has been built.
-        """
-        ParserElement.resetCache()
-        if not self.streamlined:
-            self.streamline()
-            #~ self.saveAsList = True
-        for e in self.ignoreExprs:
-            e.streamline()
-        if self.keepTabs:
-            loc, tokens = self._parse( instring, 0 )
-        else:
-            loc, tokens = self._parse( instring.expandtabs(), 0 )
-        return tokens
-
-    def scanString( self, instring, maxMatches=sys.maxint ):
-        """Scan the input string for expression matches.  Each match will return the 
-           matching tokens, start location, and end location.  May be called with optional
-           maxMatches argument, to clip scanning after 'n' matches are found."""
-        if not self.streamlined:
-            self.streamline()
-        for e in self.ignoreExprs:
-            e.streamline()
-        
-        if not self.keepTabs:
-            instring = instring.expandtabs()
-        instrlen = len(instring)
-        loc = 0
-        preparseFn = self.preParse
-        parseFn = self._parse
-        ParserElement.resetCache()
-        matches = 0
-        while loc <= instrlen and matches < maxMatches:
-            try:
-                preloc = preparseFn( instring, loc )
-                nextLoc,tokens = parseFn( instring, preloc, callPreParse=False )
-            except ParseException:
-                loc = preloc+1
-            else:
-                matches += 1
-                yield tokens, preloc, nextLoc
-                loc = nextLoc
-        
-    def transformString( self, instring ):
-        """Extension to scanString, to modify matching text with modified tokens that may
-           be returned from a parse action.  To use transformString, define a grammar and 
-           attach a parse action to it that modifies the returned token list.  
-           Invoking transformString() on a target string will then scan for matches, 
-           and replace the matched text patterns according to the logic in the parse 
-           action.  transformString() returns the resulting transformed string."""
-        out = []
-        lastE = 0
-        # force preservation of <TAB>s, to minimize unwanted transformation of string, and to
-        # keep string locs straight between transformString and scanString
-        self.keepTabs = True
-        for t,s,e in self.scanString( instring ):
-            out.append( instring[lastE:s] )
-            if t:
-                if isinstance(t,ParseResults):
-                    out += t.asList()
-                elif isinstance(t,list):
-                    out += t
-                else:
-                    out.append(t)
-            lastE = e
-        out.append(instring[lastE:])
-        return "".join(out)
-
-    def searchString( self, instring, maxMatches=sys.maxint ):
-        """Another extension to scanString, simplifying the access to the tokens found
-           to match the given parse expression.  May be called with optional
-           maxMatches argument, to clip searching after 'n' matches are found.
-        """
-        return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ])
-            
-    def __add__(self, other ):
-        """Implementation of + operator - returns And"""
-        if isinstance( other, basestring ):
-            other = Literal( other )
-        if not isinstance( other, ParserElement ):
-            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
-                    SyntaxWarning, stacklevel=2)
-        return And( [ self, other ] )
-
-    def __radd__(self, other ):
-        """Implementation of += operator"""
-        if isinstance( other, basestring ):
-            other = Literal( other )
-        if not isinstance( other, ParserElement ):
-            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
-                    SyntaxWarning, stacklevel=2)
-        return other + self
-
-    def __or__(self, other ):
-        """Implementation of | operator - returns MatchFirst"""
-        if isinstance( other, basestring ):
-            other = Literal( other )
-        if not isinstance( other, ParserElement ):
-            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
-                    SyntaxWarning, stacklevel=2)
-        return MatchFirst( [ self, other ] )
-
-    def __ror__(self, other ):
-        """Implementation of |= operator"""
-        if isinstance( other, basestring ):
-            other = Literal( other )
-        if not isinstance( other, ParserElement ):
-            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
-                    SyntaxWarning, stacklevel=2)
-        return other | self
-
-    def __xor__(self, other ):
-        """Implementation of ^ operator - returns Or"""
-        if isinstance( other, basestring ):
-            other = Literal( other )
-        if not isinstance( other, ParserElement ):
-            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
-                    SyntaxWarning, stacklevel=2)
-        return Or( [ self, other ] )
-
-    def __rxor__(self, other ):
-        """Implementation of ^= operator"""
-        if isinstance( other, basestring ):
-            other = Literal( other )
-        if not isinstance( other, ParserElement ):
-            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
-                    SyntaxWarning, stacklevel=2)
-        return other ^ self
-
-    def __and__(self, other ):
-        """Implementation of & operator - returns Each"""
-        if isinstance( other, basestring ):
-            other = Literal( other )
-        if not isinstance( other, ParserElement ):
-            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
-                    SyntaxWarning, stacklevel=2)
-        return Each( [ self, other ] )
-
-    def __rand__(self, other ):
-        """Implementation of right-& operator"""
-        if isinstance( other, basestring ):
-            other = Literal( other )
-        if not isinstance( other, ParserElement ):
-            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
-                    SyntaxWarning, stacklevel=2)
-        return other & self
-
-    def __invert__( self ):
-        """Implementation of ~ operator - returns NotAny"""
-        return NotAny( self )
-
-    def suppress( self ):
-        """Suppresses the output of this ParserElement; useful to keep punctuation from
-           cluttering up returned output.
-        """
-        return Suppress( self )
-
-    def leaveWhitespace( self ):
-        """Disables the skipping of whitespace before matching the characters in the 
-           ParserElement's defined pattern.  This is normally only used internally by
-           the pyparsing module, but may be needed in some whitespace-sensitive grammars.
-        """
-        self.skipWhitespace = False
-        return self
-
-    def setWhitespaceChars( self, chars ):
-        """Overrides the default whitespace chars
-        """
-        self.skipWhitespace = True
-        self.whiteChars = chars
-        self.copyDefaultWhiteChars = False
-        return self
-        
-    def parseWithTabs( self ):
-        """Overrides default behavior to expand <TAB>s to spaces before parsing the input string.
-           Must be called before parseString when the input grammar contains elements that 
-           match <TAB> characters."""
-        self.keepTabs = True
-        return self
-        
-    def ignore( self, other ):
-        """Define expression to be ignored (e.g., comments) while doing pattern 
-           matching; may be called repeatedly, to define multiple comment or other
-           ignorable patterns.
-        """
-        if isinstance( other, Suppress ):
-            if other not in self.ignoreExprs:
-                self.ignoreExprs.append( other )
-        else:
-            self.ignoreExprs.append( Suppress( other ) )
-        return self
-
-    def setDebugActions( self, startAction, successAction, exceptionAction ):
-        """Enable display of debugging messages while doing pattern matching."""
-        self.debugActions = (startAction or _defaultStartDebugAction, 
-                             successAction or _defaultSuccessDebugAction, 
-                             exceptionAction or _defaultExceptionDebugAction)
-        self.debug = True
-        return self
-
-    def setDebug( self, flag=True ):
-        """Enable display of debugging messages while doing pattern matching."""
-        if flag:
-            self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )
-        else:
-            self.debug = False
-        return self
-
-    def __str__( self ):
-        return self.name
-
-    def __repr__( self ):
-        return _ustr(self)
-        
-    def streamline( self ):
-        self.streamlined = True
-        self.strRepr = None
-        return self
-        
-    def checkRecursion( self, parseElementList ):
-        pass
-        
-    def validate( self, validateTrace=[] ):
-        """Check defined expressions for valid structure, check for infinite recursive definitions."""
-        self.checkRecursion( [] )
-
-    def parseFile( self, file_or_filename ):
-        """Execute the parse expression on the given file or filename.
-           If a filename is specified (instead of a file object),
-           the entire file is opened, read, and closed before parsing.
-        """
-        try:
-            file_contents = file_or_filename.read()
-        except AttributeError:
-            f = open(file_or_filename, "rb")
-            file_contents = f.read()
-            f.close()
-        return self.parseString(file_contents)
-
-
-class Token(ParserElement):
-    """Abstract ParserElement subclass, for defining atomic matching patterns."""
-    def __init__( self ):
-        super(Token,self).__init__( savelist=False )
-        self.myException = ParseException("",0,"",self)
-
-    def setName(self, name):
-        s = super(Token,self).setName(name)
-        self.errmsg = "Expected " + self.name
-        s.myException.msg = self.errmsg
-        return s
-
-
-class Empty(Token):
-    """An empty token, will always match."""
-    def __init__( self ):
-        super(Empty,self).__init__()
-        self.name = "Empty"
-        self.mayReturnEmpty = True
-        self.mayIndexError = False
-
-
-class NoMatch(Token):
-    """A token that will never match."""
-    def __init__( self ):
-        super(NoMatch,self).__init__()
-        self.name = "NoMatch"
-        self.mayReturnEmpty = True
-        self.mayIndexError = False
-        self.errmsg = "Unmatchable token"
-        self.myException.msg = self.errmsg
-        
-    def parseImpl( self, instring, loc, doActions=True ):
-        exc = self.myException
-        exc.loc = loc
-        exc.pstr = instring
-        raise exc
-
-
-class Literal(Token):
-    """Token to exactly match a specified string."""
-    def __init__( self, matchString ):
-        super(Literal,self).__init__()
-        self.match = matchString
-        self.matchLen = len(matchString)
-        try:
-            self.firstMatchChar = matchString[0]
-        except IndexError:
-            warnings.warn("null string passed to Literal; use Empty() instead", 
-                            SyntaxWarning, stacklevel=2)
-            self.__class__ = Empty
-        self.name = '"%s"' % self.match
-        self.errmsg = "Expected " + self.name
-        self.mayReturnEmpty = False
-        self.myException.msg = self.errmsg
-        self.mayIndexError = False
-
-    # Performance tuning: this routine gets called a *lot*
-    # if this is a single character match string  and the first character matches,
-    # short-circuit as quickly as possible, and avoid calling startswith
-    #~ @profile
-    def parseImpl( self, instring, loc, doActions=True ):
-        if (instring[loc] == self.firstMatchChar and
-            (self.matchLen==1 or instring.startswith(self.match,loc)) ):
-            return loc+self.matchLen, self.match
-        #~ raise ParseException( instring, loc, self.errmsg )
-        exc = self.myException
-        exc.loc = loc
-        exc.pstr = instring
-        raise exc
-
-class Keyword(Token):
-    """Token to exactly match a specified string as a keyword, that is, it must be 
-       immediately followed by a non-keyword character.  Compare with Literal::
-         Literal("if") will match the leading 'if' in 'ifAndOnlyIf'.
-         Keyword("if") will not; it will only match the leading 'if in 'if x=1', or 'if(y==2)'
-       Accepts two optional constructor arguments in addition to the keyword string:
-       identChars is a string of characters that would be valid identifier characters,
-       defaulting to all alphanumerics + "_" and "$"; caseless allows case-insensitive
-       matching, default is False.
-    """
-    DEFAULT_KEYWORD_CHARS = alphanums+"_$"
-    
-    def __init__( self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False ):
-        super(Keyword,self).__init__()
-        self.match = matchString
-        self.matchLen = len(matchString)
-        try:
-            self.firstMatchChar = matchString[0]
-        except IndexError:
-            warnings.warn("null string passed to Keyword; use Empty() instead", 
-                            SyntaxWarning, stacklevel=2)
-        self.name = '"%s"' % self.match
-        self.errmsg = "Expected " + self.name
-        self.mayReturnEmpty = False
-        self.myException.msg = self.errmsg
-        self.mayIndexError = False
-        self.caseless = caseless
-        if caseless:
-            self.caselessmatch = matchString.upper()
-            identChars = identChars.upper()
-        self.identChars = _str2dict(identChars)
-
-    def parseImpl( self, instring, loc, doActions=True ):
-        if self.caseless:
-            if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
-                 (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) and
-                 (loc == 0 or instring[loc-1].upper() not in self.identChars) ):
-                return loc+self.matchLen, self.match
-        else:
-            if (instring[loc] == self.firstMatchChar and
-                (self.matchLen==1 or instring.startswith(self.match,loc)) and
-                (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen] not in self.identChars) and
-                (loc == 0 or instring[loc-1] not in self.identChars) ):
-                return loc+self.matchLen, self.match
-        #~ raise ParseException( instring, loc, self.errmsg )
-        exc = self.myException
-        exc.loc = loc
-        exc.pstr = instring
-        raise exc
-        
-    def copy(self):
-        c = super(Keyword,self).copy()
-        c.identChars = Keyword.DEFAULT_KEYWORD_CHARS
-        return c
-        
-    def setDefaultKeywordChars( chars ):
-        """Overrides the default Keyword chars
-        """
-        Keyword.DEFAULT_KEYWORD_CHARS = chars
-    setDefaultKeywordChars = staticmethod(setDefaultKeywordChars)        
-
-
-class CaselessLiteral(Literal):
-    """Token to match a specified string, ignoring case of letters.
-       Note: the matched results will always be in the case of the given
-       match string, NOT the case of the input text.
-    """
-    def __init__( self, matchString ):
-        super(CaselessLiteral,self).__init__( matchString.upper() )
-        # Preserve the defining literal.
-        self.returnString = matchString
-        self.name = "'%s'" % self.returnString
-        self.errmsg = "Expected " + self.name
-        self.myException.msg = self.errmsg
-
-    def parseImpl( self, instring, loc, doActions=True ):
-        if instring[ loc:loc+self.matchLen ].upper() == self.match:
-            return loc+self.matchLen, self.returnString
-        #~ raise ParseException( instring, loc, self.errmsg )
-        exc = self.myException
-        exc.loc = loc
-        exc.pstr = instring
-        raise exc
-
-class CaselessKeyword(Keyword):
-    def __init__( self, matchString, identChars=Keyword.DEFAULT_KEYWORD_CHARS ):
-        super(CaselessKeyword,self).__init__( matchString, identChars, caseless=True )
-
-    def parseImpl( self, instring, loc, doActions=True ):
-        if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
-             (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) ):
-            return loc+self.matchLen, self.match
-        #~ raise ParseException( instring, loc, self.errmsg )
-        exc = self.myException
-        exc.loc = loc
-        exc.pstr = instring
-        raise exc
-
-class Word(Token):
-    """Token for matching words composed of allowed character sets.
-       Defined with string containing all allowed initial characters,
-       an optional string containing allowed body characters (if omitted,
-       defaults to the initial character set), and an optional minimum,
-       maximum, and/or exact length.
-    """
-    def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0 ):
-        super(Word,self).__init__()
-        self.initCharsOrig = initChars
-        self.initChars = _str2dict(initChars)
-        if bodyChars :
-            self.bodyCharsOrig = bodyChars
-            self.bodyChars = _str2dict(bodyChars)
-        else:
-            self.bodyCharsOrig = initChars
-            self.bodyChars = _str2dict(initChars)
-            
-        self.maxSpecified = max > 0
-
-        self.minLen = min
-
-        if max > 0:
-            self.maxLen = max
-        else:
-            self.maxLen = sys.maxint
-
-        if exact > 0:
-            self.maxLen = exact
-            self.minLen = exact
-
-        self.name = _ustr(self)
-        self.errmsg = "Expected " + self.name
-        self.myException.msg = self.errmsg
-        self.mayIndexError = False
-        
-        if ' ' not in self.initCharsOrig+self.bodyCharsOrig and (min==1 and max==0 and exact==0):
-            if self.bodyCharsOrig == self.initCharsOrig:
-                self.reString = "[%s]+" % _escapeRegexRangeChars(self.initCharsOrig)
-            elif len(self.bodyCharsOrig) == 1:
-                self.reString = "%s[%s]*" % \
-                                      (re.escape(self.initCharsOrig),
-                                      _escapeRegexRangeChars(self.bodyCharsOrig),)
-            else:
-                self.reString = "[%s][%s]*" % \
-                                      (_escapeRegexRangeChars(self.initCharsOrig),
-                                      _escapeRegexRangeChars(self.bodyCharsOrig),)
-            try:
-                self.re = re.compile( self.reString )
-            except:
-                self.re = None
-        
-    def parseImpl( self, instring, loc, doActions=True ):
-        if self.re:
-            result = self.re.match(instring,loc)
-            if not result:
-                exc = self.myException
-                exc.loc = loc
-                exc.pstr = instring
-                raise exc
-            
-            loc = result.end()
-            return loc,result.group()
-        
-        if not(instring[ loc ] in self.initChars):
-            #~ raise ParseException( instring, loc, self.errmsg )
-            exc = self.myException
-            exc.loc = loc
-            exc.pstr = instring
-            raise exc
-        start = loc
-        loc += 1
-        instrlen = len(instring)
-        bodychars = self.bodyChars
-        maxloc = start + self.maxLen
-        maxloc = min( maxloc, instrlen )
-        while loc < maxloc and instring[loc] in bodychars:
-            loc += 1
-            
-        throwException = False
-        if loc - start < self.minLen:
-            throwException = True
-        if self.maxSpecified and loc < instrlen and instring[loc] in bodychars:
-            throwException = True
-
-        if throwException:
-            #~ raise ParseException( instring, loc, self.errmsg )
-            exc = self.myException
-            exc.loc = loc
-            exc.pstr = instring
-            raise exc
-
-        return loc, instring[start:loc]
-
-    def __str__( self ):
-        try:
-            return super(Word,self).__str__()
-        except:
-            pass
-
-            
-        if self.strRepr is None:
-            
-            def charsAsStr(s):
-                if len(s)>4:
-                    return s[:4]+"..."
-                else:
-                    return s
-            
-            if ( self.initCharsOrig != self.bodyCharsOrig ):
-                self.strRepr = "W:(%s,%s)" % ( charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig) )
-            else:
-                self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig)
-
-        return self.strRepr
-
-
-class Regex(Token):
-    """Token for matching strings that match a given regular expression.
-       Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module.
-    """
-    def __init__( self, pattern, flags=0):
-        """The parameters pattern and flags are passed to the re.compile() function as-is. See the Python re module for an explanation of the acceptable patterns and flags."""
-        super(Regex,self).__init__()
-        
-        if len(pattern) == 0:
-            warnings.warn("null string passed to Regex; use Empty() instead", 
-                    SyntaxWarning, stacklevel=2)
-    
-        self.pattern = pattern
-        self.flags = flags
-        
-        try:
-            self.re = re.compile(self.pattern, self.flags)
-            self.reString = self.pattern
-        except sre_constants.error,e:
-            warnings.warn("invalid pattern (%s) passed to Regex" % pattern, 
-                SyntaxWarning, stacklevel=2)
-            raise
-
-        self.name = _ustr(self)
-        self.errmsg = "Expected " + self.name
-        self.myException.msg = self.errmsg
-        self.mayIndexError = False
-        self.mayReturnEmpty = True
-    
-    def parseImpl( self, instring, loc, doActions=True ):
-        result = self.re.match(instring,loc)
-        if not result:
-            exc = self.myException
-            exc.loc = loc
-            exc.pstr = instring
-            raise exc
-        
-        loc = result.end()
-        d = result.groupdict()
-        ret = ParseResults(result.group())
-        if d:
-            for k in d.keys():
-                ret[k] = d[k]
-        return loc,ret
-    
-    def __str__( self ):
-        try:
-            return super(Regex,self).__str__()
-        except:
-            pass
-        
-        if self.strRepr is None:
-            self.strRepr = "Re:(%s)" % repr(self.pattern)
-        
-        return self.strRepr
-
-
-class QuotedString(Token):
-    """Token for matching strings that are delimited by quoting characters.
-    """
-    def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None):
-        """
-           Defined with the following parameters:
-           - quoteChar - string of one or more characters defining the quote delimiting string
-           - escChar - character to escape quotes, typically backslash (default=None)
-           - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=None)
-           - multiline - boolean indicating whether quotes can span multiple lines (default=False)
-           - unquoteResults - boolean indicating whether the matched text should be unquoted (default=True)
-           - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=None => same as quoteChar)
-        """
-        super(QuotedString,self).__init__()
-        
-        # remove white space from quote chars - wont work anyway
-        quoteChar = quoteChar.strip()
-        if len(quoteChar) == 0:
-            warnings.warn("quoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
-            raise SyntaxError()
-        
-        if endQuoteChar is None:
-            endQuoteChar = quoteChar
-        else:
-            endQuoteChar = endQuoteChar.strip()
-            if len(endQuoteChar) == 0:
-                warnings.warn("endQuoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
-                raise SyntaxError()
-        
-        self.quoteChar = quoteChar
-        self.quoteCharLen = len(quoteChar)
-        self.firstQuoteChar = quoteChar[0]
-        self.endQuoteChar = endQuoteChar
-        self.endQuoteCharLen = len(endQuoteChar)
-        self.escChar = escChar
-        self.escQuote = escQuote
-        self.unquoteResults = unquoteResults
-        
-        if multiline:
-            self.flags = re.MULTILINE | re.DOTALL
-            self.pattern = r'%s(?:[^%s%s]' % \
-                ( re.escape(self.quoteChar),
-                  _escapeRegexRangeChars(self.endQuoteChar[0]),
-                  (escChar is not None and _escapeRegexRangeChars(escChar) or '') )
-        else:
-            self.flags = 0
-            self.pattern = r'%s(?:[^%s\n\r%s]' % \
-                ( re.escape(self.quoteChar),
-                  _escapeRegexRangeChars(self.endQuoteChar[0]),
-                  (escChar is not None and _escapeRegexRangeChars(escChar) or '') )
-        if len(self.endQuoteChar) > 1:
-            self.pattern += (
-                '|(?:' + ')|(?:'.join(["%s[^%s]" % (re.escape(self.endQuoteChar[:i]),
-                                               _escapeRegexRangeChars(self.endQuoteChar[i])) 
-                                    for i in range(len(self.endQuoteChar)-1,0,-1)]) + ')'
-                )
-        if escQuote:
-            self.pattern += (r'|(?:%s)' % re.escape(escQuote))
-        if escChar:
-            self.pattern += (r'|(?:%s.)' % re.escape(escChar))
-            self.escCharReplacePattern = re.escape(self.escChar)+"(.)"
-        self.pattern += (r')*%s' % re.escape(self.endQuoteChar))
-        
-        try:
-            self.re = re.compile(self.pattern, self.flags)
-            self.reString = self.pattern
-        except sre_constants.error,e:
-            warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern, 
-                SyntaxWarning, stacklevel=2)
-            raise
-
-        self.name = _ustr(self)
-        self.errmsg = "Expected " + self.name
-        self.myException.msg = self.errmsg
-        self.mayIndexError = False
-        self.mayReturnEmpty = True
-    
-    def parseImpl( self, instring, loc, doActions=True ):
-        result = instring[loc] == self.firstQuoteChar and self.re.match(instring,loc) or None
-        if not result:
-            exc = self.myException
-            exc.loc = loc
-            exc.pstr = instring
-            raise exc
-        
-        loc = result.end()
-        ret = result.group()
-        
-        if self.unquoteResults:
-            
-            # strip off quotes
-            ret = ret[self.quoteCharLen:-self.endQuoteCharLen]
-                
-            if isinstance(ret,basestring):
-                # replace escaped characters
-                if self.escChar:
-                    ret = re.sub(self.escCharReplacePattern,"\g<1>",ret)
-
-                # replace escaped quotes
-                if self.escQuote:
-                    ret = ret.replace(self.escQuote, self.endQuoteChar)
-
-        return loc, ret
-    
-    def __str__( self ):
-        try:
-            return super(QuotedString,self).__str__()
-        except:
-            pass
-        
-        if self.strRepr is None:
-            self.strRepr = "quoted string, starting with %s ending with %s" % (self.quoteChar, self.endQuoteChar)
-        
-        return self.strRepr
-
-
-class CharsNotIn(Token):
-    """Token for matching words composed of characters *not* in a given set.
-       Defined with string containing all disallowed characters, and an optional 
-       minimum, maximum, and/or exact length.
-    """
-    def __init__( self, notChars, min=1, max=0, exact=0 ):
-        super(CharsNotIn,self).__init__()
-        self.skipWhitespace = False
-        self.notChars = notChars
-        
-        self.minLen = min
-
-        if max > 0:
-            self.maxLen = max
-        else:
-            self.maxLen = sys.maxint
-
-        if exact > 0:
-            self.maxLen = exact
-            self.minLen = exact
-        
-        self.name = _ustr(self)
-        self.errmsg = "Expected " + self.name
-        self.mayReturnEmpty = ( self.minLen == 0 )
-        self.myException.msg = self.errmsg
-        self.mayIndexError = False
-
-    def parseImpl( self, instring, loc, doActions=True ):
-        if instring[loc] in self.notChars:
-            #~ raise ParseException( instring, loc, self.errmsg )
-            exc = self.myException
-            exc.loc = loc
-            exc.pstr = instring
-            raise exc
-            
-        start = loc
-        loc += 1
-        notchars = self.notChars
-        maxlen = min( start+self.maxLen, len(instring) )
-        while loc < maxlen and (instring[loc] not in notchars):
-            loc += 1
-
-        if loc - start < self.minLen:
-            #~ raise ParseException( instring, loc, self.errmsg )
-            exc = self.myException
-            exc.loc = loc
-            exc.pstr = instring
-            raise exc
-
-        return loc, instring[start:loc]
-
-    def __str__( self ):
-        try:
-            return super(CharsNotIn, self).__str__()
-        except:
-            pass
-
-        if self.strRepr is None:
-            if len(self.notChars) > 4:
-                self.strRepr = "!W:(%s...)" % self.notChars[:4]
-            else:
-                self.strRepr = "!W:(%s)" % self.notChars
-        
-        return self.strRepr
-
-class White(Token):
-    """Special matching class for matching whitespace.  Normally, whitespace is ignored
-       by pyparsing grammars.  This class is included when some whitespace structures
-       are significant.  Define with a string containing the whitespace characters to be
-       matched; default is " \\t\\n".  Also takes optional min, max, and exact arguments,
-       as defined for the Word class."""
-    whiteStrs = {
-        " " : "<SPC>",
-        "\t": "<TAB>",
-        "\n": "<LF>",
-        "\r": "<CR>",
-        "\f": "<FF>",
-        }
-    def __init__(self, ws=" \t\r\n", min=1, max=0, exact=0):
-        super(White,self).__init__()
-        self.matchWhite = ws
-        self.setWhitespaceChars( "".join([c for c in self.whiteChars if c not in self.matchWhite]) )
-        #~ self.leaveWhitespace()
-        self.name = ("".join([White.whiteStrs[c] for c in self.matchWhite]))
-        self.mayReturnEmpty = True
-        self.errmsg = "Expected " + self.name
-        self.myException.msg = self.errmsg
-
-        self.minLen = min
-
-        if max > 0:
-            self.maxLen = max
-        else:
-            self.maxLen = sys.maxint
-
-        if exact > 0:
-            self.maxLen = exact
-            self.minLen = exact
-            
-    def parseImpl( self, instring, loc, doActions=True ):
-        if not(instring[ loc ] in self.matchWhite):
-            #~ raise ParseException( instring, loc, self.errmsg )
-            exc = self.myException
-            exc.loc = loc
-            exc.pstr = instring
-            raise exc
-        start = loc
-        loc += 1
-        maxloc = start + self.maxLen
-        maxloc = min( maxloc, len(instring) )
-        while loc < maxloc and instring[loc] in self.matchWhite:
-            loc += 1
-
-        if loc - start < self.minLen:
-            #~ raise ParseException( instring, loc, self.errmsg )
-            exc = self.myException
-            exc.loc = loc
-            exc.pstr = instring
-            raise exc
-
-        return loc, instring[start:loc]
-
-
-class PositionToken(Token):
-    def __init__( self ):
-        super(PositionToken,self).__init__()
-        self.name=self.__class__.__name__
-        self.mayReturnEmpty = True
-        self.mayIndexError = False
-
-class GoToColumn(PositionToken):
-    """Token to advance to a specific column of input text; useful for tabular report scraping."""
-    def __init__( self, colno ):
-        super(GoToColumn,self).__init__()
-        self.col = colno
-
-    def preParse( self, instring, loc ):
-        if col(loc,instring) != self.col:
-            instrlen = len(instring)
-            if self.ignoreExprs:
-                loc = self.skipIgnorables( instring, loc )
-            while loc < instrlen and instring[loc].isspace() and col( loc, instring ) != self.col :
-                loc += 1
-        return loc
-
-    def parseImpl( self, instring, loc, doActions=True ):
-        thiscol = col( loc, instring )
-        if thiscol > self.col:
-            raise ParseException( instring, loc, "Text not in expected column", self )
-        newloc = loc + self.col - thiscol
-        ret = instring[ loc: newloc ]
-        return newloc, ret
-
-class LineStart(PositionToken):
-    """Matches if current position is at the beginning of a line within the parse string"""
-    def __init__( self ):
-        super(LineStart,self).__init__()
-        self.setWhitespaceChars( " \t" )
-        self.errmsg = "Expected start of line"
-        self.myException.msg = self.errmsg
-
-    def preParse( self, instring, loc ):
-        preloc = super(LineStart,self).preParse(instring,loc)
-        if instring[preloc] == "\n":
-            loc += 1
-        return loc
-
-    def parseImpl( self, instring, loc, doActions=True ):
-        if not( loc==0 or
-            (loc == self.preParse( instring, 0 )) or
-            (instring[loc-1] == "\n") ): #col(loc, instring) != 1:
-            #~ raise ParseException( instring, loc, "Expected start of line" )
-            exc = self.myException
-            exc.loc = loc
-            exc.pstr = instring
-            raise exc
-        return loc, []
-
-class LineEnd(PositionToken):
-    """Matches if current position is at the end of a line within the parse string"""
-    def __init__( self ):
-        super(LineEnd,self).__init__()
-        self.setWhitespaceChars( " \t" )
-        self.errmsg = "Expected end of line"
-        self.myException.msg = self.errmsg
-    
-    def parseImpl( self, instring, loc, doActions=True ):
-        if loc<len(instring):
-            if instring[loc] == "\n":
-                return loc+1, "\n"
-            else:
-                #~ raise ParseException( instring, loc, "Expected end of line" )
-                exc = self.myException
-                exc.loc = loc
-                exc.pstr = instring
-                raise exc
-        elif loc == len(instring):
-            return loc+1, []
-        else:
-            exc = self.myException
-            exc.loc = loc
-            exc.pstr = instring
-            raise exc
-
-class StringStart(PositionToken):
-    """Matches if current position is at the beginning of the parse string"""
-    def __init__( self ):
-        super(StringStart,self).__init__()
-        self.errmsg = "Expected start of text"
-        self.myException.msg = self.errmsg
-    
-    def parseImpl( self, instring, loc, doActions=True ):
-        if loc != 0:
-            # see if entire string up to here is just whitespace and ignoreables
-            if loc != self.preParse( instring, 0 ):
-                #~ raise ParseException( instring, loc, "Expected start of text" )
-                exc = self.myException
-                exc.loc = loc
-                exc.pstr = instring
-                raise exc
-        return loc, []
-
-class StringEnd(PositionToken):
-    """Matches if current position is at the end of the parse string"""
-    def __init__( self ):
-        super(StringEnd,self).__init__()
-        self.errmsg = "Expected end of text"
-        self.myException.msg = self.errmsg
-    
-    def parseImpl( self, instring, loc, doActions=True ):
-        if loc < len(instring):
-            #~ raise ParseException( instring, loc, "Expected end of text" )
-            exc = self.myException
-            exc.loc = loc
-            exc.pstr = instring
-            raise exc
-        elif loc == len(instring):
-            return loc+1, []
-        else:
-            exc = self.myException
-            exc.loc = loc
-            exc.pstr = instring
-            raise exc
-
-
-class ParseExpression(ParserElement):
-    """Abstract subclass of ParserElement, for combining and post-processing parsed tokens."""
-    def __init__( self, exprs, savelist = False ):
-        super(ParseExpression,self).__init__(savelist)
-        if isinstance( exprs, list ):
-            self.exprs = exprs
-        elif isinstance( exprs, basestring ):
-            self.exprs = [ Literal( exprs ) ]
-        else:
-            self.exprs = [ exprs ]
-
-    def __getitem__( self, i ):
-        return self.exprs[i]
-
-    def append( self, other ):
-        self.exprs.append( other )
-        self.strRepr = None
-        return self
-
-    def leaveWhitespace( self ):
-        """Extends leaveWhitespace defined in base class, and also invokes leaveWhitespace on
-           all contained expressions."""
-        self.skipWhitespace = False
-        self.exprs = [ e.copy() for e in self.exprs ]
-        for e in self.exprs:
-            e.leaveWhitespace()
-        return self
-
-    def ignore( self, other ):
-        if isinstance( other, Suppress ):
-            if other not in self.ignoreExprs:
-                super( ParseExpression, self).ignore( other )
-                for e in self.exprs:
-                    e.ignore( self.ignoreExprs[-1] )
-        else:
-            super( ParseExpression, self).ignore( other )
-            for e in self.exprs:
-                e.ignore( self.ignoreExprs[-1] )
-        return self
-
-    def __str__( self ):
-        try:
-            return super(ParseExpression,self).__str__()
-        except:
-            pass
-            
-        if self.strRepr is None:
-            self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.exprs) )
-        return self.strRepr
-
-    def streamline( self ):
-        super(ParseExpression,self).streamline()
-
-        for e in self.exprs:
-            e.streamline()
-
-        # collapse nested And's of the form And( And( And( a,b), c), d) to And( a,b,c,d )
-        # but only if there are no parse actions or resultsNames on the nested And's
-        # (likewise for Or's and MatchFirst's)
-        if ( len(self.exprs) == 2 ):
-            other = self.exprs[0]
-            if ( isinstance( other, self.__class__ ) and
-                  not(other.parseAction) and
-                  other.resultsName is None and
-                  not other.debug ):
-                self.exprs = other.exprs[:] + [ self.exprs[1] ]
-                self.strRepr = None
-                self.mayReturnEmpty |= other.mayReturnEmpty
-                self.mayIndexError  |= other.mayIndexError
-
-            other = self.exprs[-1]
-            if ( isinstance( other, self.__class__ ) and
-                  not(other.parseAction) and
-                  other.resultsName is None and
-                  not other.debug ):
-                self.exprs = self.exprs[:-1] + other.exprs[:]
-                self.strRepr = None
-                self.mayReturnEmpty |= other.mayReturnEmpty
-                self.mayIndexError  |= other.mayIndexError
-
-        return self
-
-    def setResultsName( self, name, listAllMatches=False ):
-        ret = super(ParseExpression,self).setResultsName(name,listAllMatches)
-        return ret
-    
-    def validate( self, validateTrace=[] ):
-        tmp = validateTrace[:]+[self]
-        for e in self.exprs:
-            e.validate(tmp)
-        self.checkRecursion( [] )
-
-class And(ParseExpression):
-    """Requires all given ParseExpressions to be found in the given order.
-       Expressions may be separated by whitespace.
-       May be constructed using the '+' operator.
-    """
-    def __init__( self, exprs, savelist = True ):
-        super(And,self).__init__(exprs, savelist)
-        self.mayReturnEmpty = True
-        for e in self.exprs:
-            if not e.mayReturnEmpty:
-                self.mayReturnEmpty = False
-                break
-        self.setWhitespaceChars( exprs[0].whiteChars )
-        self.skipWhitespace = exprs[0].skipWhitespace
-
-    def parseImpl( self, instring, loc, doActions=True ):
-        # pass False as last arg to _parse for first element, since we already
-        # pre-parsed the string as part of our And pre-parsing
-        loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False )
-        for e in self.exprs[1:]:
-            loc, exprtokens = e._parse( instring, loc, doActions )
-            if exprtokens or exprtokens.keys():
-                resultlist += exprtokens
-        return loc, resultlist
-
-    def __iadd__(self, other ):
-        if isinstance( other, basestring ):
-            other = Literal( other )
-        return self.append( other ) #And( [ self, other ] )
-        
-    def checkRecursion( self, parseElementList ):
-        subRecCheckList = parseElementList[:] + [ self ]
-        for e in self.exprs:
-            e.checkRecursion( subRecCheckList )
-            if not e.mayReturnEmpty:
-                break
-                
-    def __str__( self ):
-        if hasattr(self,"name"):
-            return self.name
-            
-        if self.strRepr is None:
-            self.strRepr = "{" + " ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
-        
-        return self.strRepr
-    
-
-class Or(ParseExpression):
-    """Requires that at least one ParseExpression is found.
-       If two expressions match, the expression that matches the longest string will be used.
-       May be constructed using the '^' operator.
-    """
-    def __init__( self, exprs, savelist = False ):
-        super(Or,self).__init__(exprs, savelist)
-        self.mayReturnEmpty = False
-        for e in self.exprs:
-            if e.mayReturnEmpty:
-                self.mayReturnEmpty = True
-                break
-    
-    def parseImpl( self, instring, loc, doActions=True ):
-        maxExcLoc = -1
-        maxMatchLoc = -1
-        for e in self.exprs:
-            try:
-                loc2 = e.tryParse( instring, loc )
-            except ParseException, err:
-                if err.loc > maxExcLoc:
-                    maxException = err
-                    maxExcLoc = err.loc
-            except IndexError, err:
-                if len(instring) > maxExcLoc:
-                    maxException = ParseException(instring,len(instring),e.errmsg,self)
-                    maxExcLoc = len(instring)
-            else:
-                if loc2 > maxMatchLoc:
-                    maxMatchLoc = loc2
-                    maxMatchExp = e
-        
-        if maxMatchLoc < 0:
-            if self.exprs:
-                raise maxException
-            else:
-                raise ParseException(instring, loc, "no defined alternatives to match", self)
-
-        return maxMatchExp._parse( instring, loc, doActions )
-
-    def __ixor__(self, other ):
-        if isinstance( other, basestring ):
-            other = Literal( other )
-        return self.append( other ) #Or( [ self, other ] )
-
-    def __str__( self ):
-        if hasattr(self,"name"):
-            return self.name
-            
-        if self.strRepr is None:
-            self.strRepr = "{" + " ^ ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
-        
-        return self.strRepr
-    
-    def checkRecursion( self, parseElementList ):
-        subRecCheckList = parseElementList[:] + [ self ]
-        for e in self.exprs:
-            e.checkRecursion( subRecCheckList )
-
-
-class MatchFirst(ParseExpression):
-    """Requires that at least one ParseExpression is found.
-       If two expressions match, the first one listed is the one that will match.
-       May be constructed using the '|' operator.
-    """
-    def __init__( self, exprs, savelist = False ):
-        super(MatchFirst,self).__init__(exprs, savelist)
-        if exprs:
-            self.mayReturnEmpty = False
-            for e in self.exprs:
-                if e.mayReturnEmpty:
-                    self.mayReturnEmpty = True
-                    break
-        else:
-            self.mayReturnEmpty = True
-    
-    def parseImpl( self, instring, loc, doActions=True ):
-        maxExcLoc = -1
-        for e in self.exprs:
-            try:
-                ret = e._parse( instring, loc, doActions )
-                return ret
-            except ParseException, err:
-                if err.loc > maxExcLoc:
-                    maxException = err
-                    maxExcLoc = err.loc
-            except IndexError, err:
-                if len(instring) > maxExcLoc:
-                    maxException = ParseException(instring,len(instring),e.errmsg,self)
-                    maxExcLoc = len(instring)
-
-        # only got here if no expression matched, raise exception for match that made it the furthest
-        else:
-            if self.exprs:
-                raise maxException
-            else:
-                raise ParseException(instring, loc, "no defined alternatives to match", self)
-
-    def __ior__(self, other ):
-        if isinstance( other, basestring ):
-            other = Literal( other )
-        return self.append( other ) #MatchFirst( [ self, other ] )
-
-    def __str__( self ):
-        if hasattr(self,"name"):
-            return self.name
-            
-        if self.strRepr is None:
-            self.strRepr = "{" + " | ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
-        
-        return self.strRepr
-    
-    def checkRecursion( self, parseElementList ):
-        subRecCheckList = parseElementList[:] + [ self ]
-        for e in self.exprs:
-            e.checkRecursion( subRecCheckList )
-
-class Each(ParseExpression):
-    """Requires all given ParseExpressions to be found, but in any order.
-       Expressions may be separated by whitespace.
-       May be constructed using the '&' operator.
-    """
-    def __init__( self, exprs, savelist = True ):
-        super(Each,self).__init__(exprs, savelist)
-        self.mayReturnEmpty = True
-        for e in self.exprs:
-            if not e.mayReturnEmpty:
-                self.mayReturnEmpty = False
-                break
-        self.skipWhitespace = True
-        self.optionals = [ e.expr for e in exprs if isinstance(e,Optional) ]
-        self.multioptionals = [ e.expr for e in exprs if isinstance(e,ZeroOrMore) ]
-        self.multirequired = [ e.expr for e in exprs if isinstance(e,OneOrMore) ]
-        self.required = [ e for e in exprs if not isinstance(e,(Optional,ZeroOrMore,OneOrMore)) ]
-        self.required += self.multirequired
-
-    def parseImpl( self, instring, loc, doActions=True ):
-        tmpLoc = loc
-        tmpReqd = self.required[:]
-        tmpOpt  = self.optionals[:]
-        matchOrder = []
-
-        keepMatching = True
-        while keepMatching:
-            tmpExprs = tmpReqd + tmpOpt + self.multioptionals + self.multirequired
-            failed = []
-            for e in tmpExprs:
-                try:
-                    tmpLoc = e.tryParse( instring, tmpLoc )
-                except ParseException:
-                    failed.append(e)
-                else:
-                    matchOrder.append(e)
-                    if e in tmpReqd:
-                        tmpReqd.remove(e)
-                    elif e in tmpOpt:
-                        tmpOpt.remove(e)
-            if len(failed) == len(tmpExprs):
-                keepMatching = False
-        
-        if tmpReqd:
-            missing = ", ".join( [ _ustr(e) for e in tmpReqd ] )
-            raise ParseException(instring,loc,"Missing one or more required elements (%s)" % missing )
-
-        resultlist = []
-        for e in matchOrder:
-            loc,results = e._parse(instring,loc,doActions)
-            resultlist.append(results)
-            
-        finalResults = ParseResults([])
-        for r in resultlist:
-            dups = {}
-            for k in r.keys():
-                if k in finalResults.keys():
-                    tmp = ParseResults(finalResults[k])
-                    tmp += ParseResults(r[k])
-                    dups[k] = tmp
-            finalResults += ParseResults(r)
-            for k,v in dups.items():
-                finalResults[k] = v
-        return loc, finalResults
-
-    def __str__( self ):
-        if hasattr(self,"name"):
-            return self.name
-            
-        if self.strRepr is None:
-            self.strRepr = "{" + " & ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
-        
-        return self.strRepr
-    
-    def checkRecursion( self, parseElementList ):
-        subRecCheckList = parseElementList[:] + [ self ]
-        for e in self.exprs:
-            e.checkRecursion( subRecCheckList )
-
-
-class ParseElementEnhance(ParserElement):
-    """Abstract subclass of ParserElement, for combining and post-processing parsed tokens."""
-    def __init__( self, expr, savelist=False ):
-        super(ParseElementEnhance,self).__init__(savelist)
-        if isinstance( expr, basestring ):
-            expr = Literal(expr)
-        self.expr = expr
-        self.strRepr = None
-        if expr is not None:
-            self.mayIndexError = expr.mayIndexError
-            self.setWhitespaceChars( expr.whiteChars )
-            self.skipWhitespace = expr.skipWhitespace
-            self.saveAsList = expr.saveAsList
-    
-    def parseImpl( self, instring, loc, doActions=True ):
-        if self.expr is not None:
-            return self.expr._parse( instring, loc, doActions, callPreParse=False )
-        else:
-            raise ParseException("",loc,self.errmsg,self)
-            
-    def leaveWhitespace( self ):
-        self.skipWhitespace = False
-        self.expr = self.expr.copy()
-        if self.expr is not None:
-            self.expr.leaveWhitespace()
-        return self
-
-    def ignore( self, other ):
-        if isinstance( other, Suppress ):
-            if other not in self.ignoreExprs:
-                super( ParseElementEnhance, self).ignore( other )
-                if self.expr is not None:
-                    self.expr.ignore( self.ignoreExprs[-1] )
-        else:
-            super( ParseElementEnhance, self).ignore( other )
-            if self.expr is not None:
-                self.expr.ignore( self.ignoreExprs[-1] )
-        return self
-
-    def streamline( self ):
-        super(ParseElementEnhance,self).streamline()
-        if self.expr is not None:
-            self.expr.streamline()
-        return self
-
-    def checkRecursion( self, parseElementList ):
-        if self in parseElementList:
-            raise RecursiveGrammarException( parseElementList+[self] )
-        subRecCheckList = parseElementList[:] + [ self ]
-        if self.expr is not None:
-            self.expr.checkRecursion( subRecCheckList )
-        
-    def validate( self, validateTrace=[] ):
-        tmp = validateTrace[:]+[self]
-        if self.expr is not None:
-            self.expr.validate(tmp)
-        self.checkRecursion( [] )
-    
-    def __str__( self ):
-        try:
-            return super(ParseElementEnhance,self).__str__()
-        except:
-            pass
-            
-        if self.strRepr is None and self.expr is not None:
-            self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.expr) )
-        return self.strRepr
-
-
-class FollowedBy(ParseElementEnhance):
-    """Lookahead matching of the given parse expression.  FollowedBy
-    does *not* advance the parsing position within the input string, it only 
-    verifies that the specified parse expression matches at the current 
-    position.  FollowedBy always returns a null token list."""
-    def __init__( self, expr ):
-        super(FollowedBy,self).__init__(expr)
-        self.mayReturnEmpty = True
-        
-    def parseImpl( self, instring, loc, doActions=True ):
-        self.expr.tryParse( instring, loc )
-        return loc, []
-
-
-class NotAny(ParseElementEnhance):
-    """Lookahead to disallow matching with the given parse expression.  NotAny
-    does *not* advance the parsing position within the input string, it only 
-    verifies that the specified parse expression does *not* match at the current 
-    position.  Also, NotAny does *not* skip over leading whitespace. NotAny 
-    always returns a null token list.  May be constructed using the '~' operator."""
-    def __init__( self, expr ):
-        super(NotAny,self).__init__(expr)
-        #~ self.leaveWhitespace()
-        self.skipWhitespace = False  # do NOT use self.leaveWhitespace(), don't want to propagate to exprs
-        self.mayReturnEmpty = True
-        self.errmsg = "Found unwanted token, "+_ustr(self.expr)
-        self.myException = ParseException("",0,self.errmsg,self)
-        
-    def parseImpl( self, instring, loc, doActions=True ):
-        try:
-            self.expr.tryParse( instring, loc )
-        except (ParseException,IndexError):
-            pass
-        else:
-            #~ raise ParseException(instring, loc, self.errmsg )
-            exc = self.myException
-            exc.loc = loc
-            exc.pstr = instring
-            raise exc
-        return loc, []
-
-    def __str__( self ):
-        if hasattr(self,"name"):
-            return self.name
-            
-        if self.strRepr is None:
-            self.strRepr = "~{" + _ustr(self.expr) + "}"
-        
-        return self.strRepr
-
-
-class ZeroOrMore(ParseElementEnhance):
-    """Optional repetition of zero or more of the given expression."""
-    def __init__( self, expr ):
-        super(ZeroOrMore,self).__init__(expr)
-        self.mayReturnEmpty = True
-    
-    def parseImpl( self, instring, loc, doActions=True ):
-        tokens = []
-        try:
-            loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
-            hasIgnoreExprs = ( len(self.ignoreExprs) > 0 )
-            while 1:
-                if hasIgnoreExprs:
-                    preloc = self.skipIgnorables( instring, loc )
-                else:
-                    preloc = loc
-                loc, tmptokens = self.expr._parse( instring, preloc, doActions )
-                if tmptokens or tmptokens.keys():
-                    tokens += tmptokens
-        except (ParseException,IndexError):
-            pass
-
-        return loc, tokens
-
-    def __str__( self ):
-        if hasattr(self,"name"):
-            return self.name
-            
-        if self.strRepr is None:
-            self.strRepr = "[" + _ustr(self.expr) + "]..."
-        
-        return self.strRepr
-    
-    def setResultsName( self, name, listAllMatches=False ):
-        ret = super(ZeroOrMore,self).setResultsName(name,listAllMatches)
-        ret.saveAsList = True
-        return ret
-    
-
-class OneOrMore(ParseElementEnhance):
-    """Repetition of one or more of the given expression."""
-    def parseImpl( self, instring, loc, doActions=True ):
-        # must be at least one
-        loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
-        try:
-            hasIgnoreExprs = ( len(self.ignoreExprs) > 0 )
-            while 1:
-                if hasIgnoreExprs:
-                    preloc = self.skipIgnorables( instring, loc )
-                else:
-                    preloc = loc
-                loc, tmptokens = self.expr._parse( instring, preloc, doActions )
-                if tmptokens or tmptokens.keys():
-                    tokens += tmptokens
-        except (ParseException,IndexError):
-            pass
-
-        return loc, tokens
-
-    def __str__( self ):
-        if hasattr(self,"name"):
-            return self.name
-            
-        if self.strRepr is None:
-            self.strRepr = "{" + _ustr(self.expr) + "}..."
-        
-        return self.strRepr
-    
-    def setResultsName( self, name, listAllMatches=False ):
-        ret = super(OneOrMore,self).setResultsName(name,listAllMatches)
-        ret.saveAsList = True
-        return ret
-
-class _NullToken(object):
-    def __bool__(self):
-        return False
-    def __str__(self):
-        return ""
-
-_optionalNotMatched = _NullToken()
-class Optional(ParseElementEnhance):
-    """Optional matching of the given expression.
-       A default return string can also be specified, if the optional expression
-       is not found.
-    """
-    def __init__( self, exprs, default=_optionalNotMatched ):
-        super(Optional,self).__init__( exprs, savelist=False )
-        self.defaultValue = default
-        self.mayReturnEmpty = True
-
-    def parseImpl( self, instring, loc, doActions=True ):
-        try:
-            loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
-        except (ParseException,IndexError):
-            if self.defaultValue is not _optionalNotMatched:
-                tokens = [ self.defaultValue ]
-            else:
-                tokens = []
-        return loc, tokens
-
-    def __str__( self ):
-        if hasattr(self,"name"):
-            return self.name
-            
-        if self.strRepr is None:
-            self.strRepr = "[" + _ustr(self.expr) + "]"
-        
-        return self.strRepr
-
-
-class SkipTo(ParseElementEnhance):
-    """Token for skipping over all undefined text until the matched expression is found.
-       If include is set to true, the matched expression is also consumed.  The ignore
-       argument is used to define grammars (typically quoted strings and comments) that 
-       might contain false matches.
-    """
-    def __init__( self, other, include=False, ignore=None ):
-        super( SkipTo, self ).__init__( other )
-        if ignore is not None:
-            self.expr = self.expr.copy()
-            self.expr.ignore(ignore)
-        self.mayReturnEmpty = True
-        self.mayIndexError = False
-        self.includeMatch = include
-        self.asList = False
-        self.errmsg = "No match found for "+_ustr(self.expr)
-        self.myException = ParseException("",0,self.errmsg,self)
-
-    def parseImpl( self, instring, loc, doActions=True ):
-        startLoc = loc
-        instrlen = len(instring)
-        expr = self.expr
-        while loc <= instrlen:
-            try:
-                loc = expr.skipIgnorables( instring, loc )
-                expr._parse( instring, loc, doActions=False, callPreParse=False )
-                if self.includeMatch:
-                    skipText = instring[startLoc:loc]
-                    loc,mat = expr._parse(instring,loc)
-                    if mat:
-                        return loc, [ skipText, mat ]
-                    else:
-                        return loc, [ skipText ]
-                else:
-                    return loc, [ instring[startLoc:loc] ]
-            except (ParseException,IndexError):
-                loc += 1
-        exc = self.myException
-        exc.loc = loc
-        exc.pstr = instring
-        raise exc
-
-class Forward(ParseElementEnhance):
-    """Forward declaration of an expression to be defined later -
-       used for recursive grammars, such as algebraic infix notation.
-       When the expression is known, it is assigned to the Forward variable using the '<<' operator.
-       
-       Note: take care when assigning to Forward not to overlook precedence of operators.
-       Specifically, '|' has a lower precedence than '<<', so that::
-          fwdExpr << a | b | c
-       will actually be evaluated as::
-          (fwdExpr << a) | b | c
-       thereby leaving b and c out as parseable alternatives.  It is recommended that you
-       explicitly group the values inserted into the Forward::
-          fwdExpr << (a | b | c)
-    """
-    def __init__( self, other=None ):
-        super(Forward,self).__init__( other, savelist=False )
-
-    def __lshift__( self, other ):
-        if isinstance( other, basestring ):
-            other = Literal(other)
-        self.expr = other
-        self.mayReturnEmpty = other.mayReturnEmpty
-        self.strRepr = None
-        return self
-
-    def leaveWhitespace( self ):
-        self.skipWhitespace = False
-        return self
-
-    def streamline( self ):
-        if not self.streamlined:
-            self.streamlined = True
-            if self.expr is not None: 
-                self.expr.streamline()
-        return self
-
-    def validate( self, validateTrace=[] ):
-        if self not in validateTrace:
-            tmp = validateTrace[:]+[self]
-            if self.expr is not None: 
-                self.expr.validate(tmp)
-        self.checkRecursion([])        
-        
-    def __str__( self ):
-        if hasattr(self,"name"):
-            return self.name
-
-        self.__class__ = _ForwardNoRecurse
-        try:
-            if self.expr is not None: 
-                retString = _ustr(self.expr)
-            else:
-                retString = "None"
-        finally:
-            self.__class__ = Forward
-        return "Forward: "+retString
-        
-    def copy(self):
-        if self.expr is not None:
-            return super(Forward,self).copy()
-        else:
-            ret = Forward()
-            ret << self
-            return ret
-
-class _ForwardNoRecurse(Forward):
-    def __str__( self ):
-        return "..."
-        
-class TokenConverter(ParseElementEnhance):
-    """Abstract subclass of ParseExpression, for converting parsed results."""
-    def __init__( self, expr, savelist=False ):
-        super(TokenConverter,self).__init__( expr )#, savelist )
-        self.saveAsList = False
-
-
-class Upcase(TokenConverter):
-    """Converter to upper case all matching tokens."""
-    def __init__(self, *args):
-        super(Upcase,self).__init__(*args)
-        warnings.warn("Upcase class is deprecated, use upcaseTokens parse action instead", 
-                       DeprecationWarning,stacklevel=2)
-    
-    def postParse( self, instring, loc, tokenlist ):
-        return map( string.upper, tokenlist )
-
-
-class Combine(TokenConverter):
-    """Converter to concatenate all matching tokens to a single string.
-       By default, the matching patterns must also be contiguous in the input string;
-       this can be disabled by specifying 'adjacent=False' in the constructor.
-    """
-    def __init__( self, expr, joinString="", adjacent=True ):
-        super(Combine,self).__init__( expr )
-        # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself
-        if adjacent:
-            self.leaveWhitespace()
-        self.adjacent = adjacent
-        self.skipWhitespace = True
-        self.joinString = joinString
-
-    def ignore( self, other ):
-        if self.adjacent:
-            ParserElement.ignore(self, other)
-        else:
-            super( Combine, self).ignore( other )
-        return self
-
-    def postParse( self, instring, loc, tokenlist ):
-        retToks = tokenlist.copy()
-        del retToks[:]
-        retToks += ParseResults([ "".join(tokenlist._asStringList(self.joinString)) ], modal=self.modalResults)
-
-        if self.resultsName and len(retToks.keys())>0:
-            return [ retToks ]
-        else:
-            return retToks
-
-class Group(TokenConverter):
-    """Converter to return the matched tokens as a list - useful for returning tokens of ZeroOrMore and OneOrMore expressions."""
-    def __init__( self, expr ):
-        super(Group,self).__init__( expr )
-        self.saveAsList = True
-
-    def postParse( self, instring, loc, tokenlist ):
-        return [ tokenlist ]
-        
-class Dict(TokenConverter):
-    """Converter to return a repetitive expression as a list, but also as a dictionary.
-       Each element can also be referenced using the first token in the expression as its key.
-       Useful for tabular report scraping when the first column can be used as a item key.
-    """
-    def __init__( self, exprs ):
-        super(Dict,self).__init__( exprs )
-        self.saveAsList = True
-
-    def postParse( self, instring, loc, tokenlist ):
-        for i,tok in enumerate(tokenlist):
-            ikey = _ustr(tok[0]).strip()
-            if len(tok)==1:
-                tokenlist[ikey] = ("",i)
-            elif len(tok)==2 and not isinstance(tok[1],ParseResults):
-                tokenlist[ikey] = (tok[1],i)
-            else:
-                dictvalue = tok.copy() #ParseResults(i)
-                del dictvalue[0]
-                if len(dictvalue)!= 1 or (isinstance(dictvalue,ParseResults) and dictvalue.keys()):
-                    tokenlist[ikey] = (dictvalue,i)
-                else:
-                    tokenlist[ikey] = (dictvalue[0],i)
-
-        if self.resultsName:
-            return [ tokenlist ]
-        else:
-            return tokenlist
-
-
-class Suppress(TokenConverter):
-    """Converter for ignoring the results of a parsed expression."""
-    def postParse( self, instring, loc, tokenlist ):
-        return []
-    
-    def suppress( self ):
-        return self
-
-
-class OnlyOnce(object):
-    """Wrapper for parse actions, to ensure they are only called once."""
-    def __init__(self, methodCall):
-        self.callable = ParserElement.normalizeParseActionArgs(methodCall)
-        self.called = False
-    def __call__(self,s,l,t):
-        if not self.called:
-            results = self.callable(s,l,t)
-            self.called = True
-            return results
-        raise ParseException(s,l,"")
-    def reset():
-        self.called = False
-
-def traceParseAction(f):
-    """Decorator for debugging parse actions."""
-    f = ParserElement.normalizeParseActionArgs(f)
-    def z(*paArgs):
-        thisFunc = f.func_name
-        s,l,t = paArgs[-3:]
-        if len(paArgs)>3:
-            thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc
-        sys.stderr.write( ">>entering %s(line: '%s', %d, %s)\n" % (thisFunc,line(l,s),l,t) )
-        try:
-            ret = f(*paArgs)
-        except Exception, exc:
-            sys.stderr.write( "<<leaving %s (exception: %s)\n" % (thisFunc,exc) )
-            raise
-        sys.stderr.write( "<<leaving %s (ret: %s)\n" % (thisFunc,ret) )
-        return ret
-    return z
-        
-#
-# global helpers
-#
-def delimitedList( expr, delim=",", combine=False ):
-    """Helper to define a delimited list of expressions - the delimiter defaults to ','.
-       By default, the list elements and delimiters can have intervening whitespace, and 
-       comments, but this can be overridden by passing 'combine=True' in the constructor.
-       If combine is set to True, the matching tokens are returned as a single token
-       string, with the delimiters included; otherwise, the matching tokens are returned
-       as a list of tokens, with the delimiters suppressed.
-    """
-    dlName = _ustr(expr)+" ["+_ustr(delim)+" "+_ustr(expr)+"]..."
-    if combine:
-        return Combine( expr + ZeroOrMore( delim + expr ) ).setName(dlName)
-    else:
-        return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName)
-
-def countedArray( expr ):
-    """Helper to define a counted list of expressions.
-       This helper defines a pattern of the form::
-           integer expr expr expr...
-       where the leading integer tells how many expr expressions follow.
-       The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed.
-    """
-    arrayExpr = Forward()
-    def countFieldParseAction(s,l,t):
-        n = int(t[0])
-        arrayExpr << (n and Group(And([expr]*n)) or Group(empty))
-        return []
-    return ( Word(nums).setParseAction(countFieldParseAction) + arrayExpr )
-
-def _flatten(L):
-    if type(L) is not list: return [L]
-    if L == []: return L
-    return _flatten(L[0]) + _flatten(L[1:])
-
-def matchPreviousLiteral(expr):
-    """Helper to define an expression that is indirectly defined from
-       the tokens matched in a previous expression, that is, it looks
-       for a 'repeat' of a previous expression.  For example::
-           first = Word(nums)
-           second = matchPreviousLiteral(first)
-           matchExpr = first + ":" + second
-       will match "1:1", but not "1:2".  Because this matches a 
-       previous literal, will also match the leading "1:1" in "1:10".  
-       If this is not desired, use matchPreviousExpr.
-       Do *not* use with packrat parsing enabled.
-    """
-    rep = Forward()
-    def copyTokenToRepeater(s,l,t):
-        if t:
-            if len(t) == 1:
-                rep << t[0]
-            else:
-                # flatten t tokens
-                tflat = _flatten(t.asList())
-                rep << And( [ Literal(tt) for tt in tflat ] )
-        else:
-            rep << Empty()
-    expr.addParseAction(copyTokenToRepeater)
-    return rep
-    
-def matchPreviousExpr(expr):
-    """Helper to define an expression that is indirectly defined from
-       the tokens matched in a previous expression, that is, it looks
-       for a 'repeat' of a previous expression.  For example::
-           first = Word(nums)
-           second = matchPreviousExpr(first)
-           matchExpr = first + ":" + second
-       will match "1:1", but not "1:2".  Because this matches by
-       expressions, will *not* match the leading "1:1" in "1:10";
-       the expressions are evaluated first, and then compared, so
-       "1" is compared with "10".
-       Do *not* use with packrat parsing enabled.
-    """
-    rep = Forward()
-    e2 = expr.copy()
-    rep << e2
-    def copyTokenToRepeater(s,l,t):
-        matchTokens = _flatten(t.asList())
-        def mustMatchTheseTokens(s,l,t):
-            theseTokens = _flatten(t.asList())
-            if  theseTokens != matchTokens:
-                raise ParseException("",0,"")
-        rep.setParseAction( mustMatchTheseTokens )
-    expr.addParseAction(copyTokenToRepeater)
-    return rep
-    
-def _escapeRegexRangeChars(s):
-    #~  escape these chars: ^-]
-    for c in r"\^-]":
-        s = s.replace(c,"\\"+c)
-    s = s.replace("\n",r"\n")
-    s = s.replace("\t",r"\t")
-    return _ustr(s)
-    
-def oneOf( strs, caseless=False, useRegex=True ):
-    """Helper to quickly define a set of alternative Literals, and makes sure to do 
-       longest-first testing when there is a conflict, regardless of the input order, 
-       but returns a MatchFirst for best performance.  
-       
-       Parameters:
-        - strs - a string of space-delimited literals, or a list of string literals
-        - caseless - (default=False) - treat all literals as caseless
-        - useRegex - (default=True) - as an optimization, will generate a Regex
-          object; otherwise, will generate a MatchFirst object (if caseless=True, or
-          if creating a Regex raises an exception)
-    """
-    if caseless:
-        isequal = ( lambda a,b: a.upper() == b.upper() )
-        masks = ( lambda a,b: b.upper().startswith(a.upper()) )
-        parseElementClass = CaselessLiteral
-    else:
-        isequal = ( lambda a,b: a == b )
-        masks = ( lambda a,b: b.startswith(a) )
-        parseElementClass = Literal
-    
-    if isinstance(strs,(list,tuple)):
-        symbols = strs[:]
-    elif isinstance(strs,basestring):
-        symbols = strs.split()
-    else:
-        warnings.warn("Invalid argument to oneOf, expected string or list",
-                SyntaxWarning, stacklevel=2)
-        
-    i = 0
-    while i < len(symbols)-1:
-        cur = symbols[i]
-        for j,other in enumerate(symbols[i+1:]):
-            if ( isequal(other, cur) ):
-                del symbols[i+j+1]
-                break
-            elif ( masks(cur, other) ):
-                del symbols[i+j+1]
-                symbols.insert(i,other)
-                cur = other
-                break
-        else:
-            i += 1
-
-    if not caseless and useRegex:
-        #~ print strs,"->", "|".join( [ _escapeRegexChars(sym) for sym in symbols] )
-        try:
-            if len(symbols)==len("".join(symbols)):
-                return Regex( "[%s]" % "".join( [ _escapeRegexRangeChars(sym) for sym in symbols] ) )
-            else:
-                return Regex( "|".join( [ re.escape(sym) for sym in symbols] ) )
-        except:
-            warnings.warn("Exception creating Regex for oneOf, building MatchFirst",
-                    SyntaxWarning, stacklevel=2)
-
-
-    # last resort, just use MatchFirst
-    return MatchFirst( [ parseElementClass(sym) for sym in symbols ] )
-
-def dictOf( key, value ):
-    """Helper to easily and clearly define a dictionary by specifying the respective patterns
-       for the key and value.  Takes care of defining the Dict, ZeroOrMore, and Group tokens
-       in the proper order.  The key pattern can include delimiting markers or punctuation,
-       as long as they are suppressed, thereby leaving the significant key text.  The value
-       pattern can include named results, so that the Dict results can include named token 
-       fields.
-    """
-    return Dict( ZeroOrMore( Group ( key + value ) ) )
-
-_bslash = "\\"
-printables = "".join( [ c for c in string.printable if c not in string.whitespace ] )
-
-# convenience constants for positional expressions
-empty       = Empty().setName("empty")
-lineStart   = LineStart().setName("lineStart")
-lineEnd     = LineEnd().setName("lineEnd")
-stringStart = StringStart().setName("stringStart")
-stringEnd   = StringEnd().setName("stringEnd")
-
-_escapedPunc = Word( _bslash, r"\[]-*.$+^?()~ ", exact=2 ).setParseAction(lambda s,l,t:t[0][1])
-_printables_less_backslash = "".join([ c for c in printables if c not in  r"\]" ])
-_escapedHexChar = Combine( Suppress(_bslash + "0x") + Word(hexnums) ).setParseAction(lambda s,l,t:unichr(int(t[0],16)))
-_escapedOctChar = Combine( Suppress(_bslash) + Word("0","01234567") ).setParseAction(lambda s,l,t:unichr(int(t[0],8)))
-_singleChar = _escapedPunc | _escapedHexChar | _escapedOctChar | Word(_printables_less_backslash,exact=1)
-_charRange = Group(_singleChar + Suppress("-") + _singleChar)
-_reBracketExpr = "[" + Optional("^").setResultsName("negate") + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") + "]"
-
-_expanded = lambda p: (isinstance(p,ParseResults) and ''.join([ unichr(c) for c in range(ord(p[0]),ord(p[1])+1) ]) or p)
-        
-def srange(s):
-    r"""Helper to easily define string ranges for use in Word construction.  Borrows
-       syntax from regexp '[]' string range definitions::
-          srange("[0-9]")   -> "0123456789"
-          srange("[a-z]")   -> "abcdefghijklmnopqrstuvwxyz"
-          srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
-       The input string must be enclosed in []'s, and the returned string is the expanded 
-       character set joined into a single string.
-       The values enclosed in the []'s may be::
-          a single character
-          an escaped character with a leading backslash (such as \- or \])
-          an escaped hex character with a leading '\0x' (\0x21, which is a '!' character)
-          an escaped octal character with a leading '\0' (\041, which is a '!' character)
-          a range of any of the above, separated by a dash ('a-z', etc.)
-          any combination of the above ('aeiouy', 'a-zA-Z0-9_$', etc.)
-    """
-    try:
-        return "".join([_expanded(part) for part in _reBracketExpr.parseString(s).body])
-    except:
-        return ""
-
-def replaceWith(replStr):
-    """Helper method for common parse actions that simply return a literal value.  Especially 
-       useful when used with transformString().
-    """
-    def _replFunc(*args):
-        return [replStr]
-    return _replFunc
-
-def removeQuotes(s,l,t):
-    """Helper parse action for removing quotation marks from parsed quoted strings.
-       To use, add this parse action to quoted string using::
-         quotedString.setParseAction( removeQuotes )
-    """
-    return t[0][1:-1]
-
-def upcaseTokens(s,l,t):
-    """Helper parse action to convert tokens to upper case."""
-    return [ str(tt).upper() for tt in t ]
-
-def downcaseTokens(s,l,t):
-    """Helper parse action to convert tokens to lower case."""
-    return [ str(tt).lower() for tt in t ]
-
-def keepOriginalText(s,startLoc,t):
-    import inspect
-    """Helper parse action to preserve original parsed text,
-       overriding any nested parse actions."""
-    f = inspect.stack()[1][0]
-    try:
-        endloc = f.f_locals["loc"]
-    finally:
-        del f
-    return s[startLoc:endloc]
-        
-def _makeTags(tagStr, xml):
-    """Internal helper to construct opening and closing tag expressions, given a tag name"""
-    if isinstance(tagStr,basestring):
-        resname = tagStr
-        tagStr = Keyword(tagStr, caseless=not xml)
-    else:
-        resname = tagStr.name
-        
-    tagAttrName = Word(alphas,alphanums+"_-")
-    if (xml):
-        tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes )
-        openTag = Suppress("<") + tagStr + \
-                Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \
-                Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
-    else:
-        printablesLessRAbrack = "".join( [ c for c in printables if c not in ">" ] )
-        tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack)
-        openTag = Suppress("<") + tagStr + \
-                Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \
-                Suppress("=") + tagAttrValue ))) + \
-                Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
-    closeTag = Combine("</" + tagStr + ">")
-    
-    openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % tagStr)
-    closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("</%s>" % tagStr)
-    
-    return openTag, closeTag
-
-def makeHTMLTags(tagStr):
-    """Helper to construct opening and closing tag expressions for HTML, given a tag name"""
-    return _makeTags( tagStr, False )
-
-def makeXMLTags(tagStr):
-    """Helper to construct opening and closing tag expressions for XML, given a tag name"""
-    return _makeTags( tagStr, True )
-
-opAssoc = _Constants()
-opAssoc.LEFT = object()
-opAssoc.RIGHT = object()
-
-def operatorPrecedence( baseExpr, opList ):
-    """Helper method for constructing grammars of expressions made up of 
-       operators working in a precedence hierarchy.  Operators may be unary or
-       binary, left- or right-associative.  Parse actions can also be attached
-       to operator expressions.
-        
-       Parameters:
-        - baseExpr - expression representing the most basic element for the nested 
-        - opList - list of tuples, one for each operator precedence level in the expression grammar; each tuple is of the form
-          (opExpr, numTerms, rightLeftAssoc, parseAction), where:
-           - opExpr is the pyparsing expression for the operator;
-              may also be a string, which will be converted to a Literal
-           - numTerms is the number of terms for this operator (must
-              be 1 or 2)
-           - rightLeftAssoc is the indicator whether the operator is
-              right or left associative, using the pyparsing-defined
-              constants opAssoc.RIGHT and opAssoc.LEFT.
-           - parseAction is the parse action to be associated with 
-              expressions matching this operator expression (the
-              parse action tuple member may be omitted)
-    """
-    ret = Forward()
-    lastExpr = baseExpr | ( Suppress('(') + ret + Suppress(')') )
-    for i,operDef in enumerate(opList):
-        opExpr,arity,rightLeftAssoc,pa = (operDef + (None,))[:4]
-        thisExpr = Forward().setName("expr%d" % i)
-        if rightLeftAssoc == opAssoc.LEFT:
-            if arity == 1:
-                matchExpr = Group( lastExpr + opExpr )
-            elif arity == 2:
-                matchExpr = Group( lastExpr + OneOrMore( opExpr + lastExpr ) )
-            else:
-                raise ValueError, "operator must be unary (1) or binary (2)"
-        elif rightLeftAssoc == opAssoc.RIGHT:
-            if arity == 1:
-                # try to avoid LR with this extra test
-                if not isinstance(opExpr, Optional):
-                    opExpr = Optional(opExpr)
-                matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group( opExpr + thisExpr ) 
-            elif arity == 2:
-                matchExpr = Group( lastExpr + OneOrMore( opExpr + thisExpr ) )
-            else:
-                raise ValueError, "operator must be unary (1) or binary (2)"
-        else:
-            raise ValueError, "operator must indicate right or left associativity"
-        if pa:
-            matchExpr.setParseAction( pa )
-        thisExpr << ( matchExpr | lastExpr )
-        lastExpr = thisExpr
-    ret << lastExpr
-    return ret
-
-alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]")
-punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]")
-
-dblQuotedString = Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\.))*"').setName("string enclosed in double quotes")
-sglQuotedString = Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\.))*'").setName("string enclosed in single quotes")
-quotedString = Regex(r'''(?:"(?:[^"\n\r\\]|(?:"")|(?:\\.))*")|(?:'(?:[^'\n\r\\]|(?:'')|(?:\\.))*')''').setName("quotedString using single or double quotes")
-
-anyOpenTag,anyCloseTag = makeHTMLTags(Word(alphas,alphanums+"_"))
-commonHTMLEntity = Combine("&" + oneOf("gt lt amp nbsp quot").setResultsName("entity") +";")
-_htmlEntityMap = dict(zip("gt lt amp nbsp quot".split(),"><& '"))
-replaceHTMLEntity = lambda t : t.entity in _htmlEntityMap and _htmlEntityMap[t.entity] or None
-    
-# it's easy to get these comment structures wrong - they're very common, so may as well make them available
-cStyleComment = Regex(r"/\*(?:[^*]*\*+)+?/").setName("C style comment")
-
-htmlComment = Regex(r"<!--[\s\S]*?-->")
-restOfLine = Regex(r".*").leaveWhitespace()
-dblSlashComment = Regex(r"\/\/(\\\n|.)*").setName("// comment")
-cppStyleComment = Regex(r"/(?:\*(?:[^*]*\*+)+?/|/[^\n]*(?:\n[^\n]*)*?(?:(?<!\\)|\Z))").setName("C++ style comment")
-
-javaStyleComment = cppStyleComment
-pythonStyleComment = Regex(r"#.*").setName("Python style comment")
-_noncomma = "".join( [ c for c in printables if c != "," ] )
-_commasepitem = Combine(OneOrMore(Word(_noncomma) + 
-                                  Optional( Word(" \t") + 
-                                            ~Literal(",") + ~LineEnd() ) ) ).streamline().setName("commaItem")
-commaSeparatedList = delimitedList( Optional( quotedString | _commasepitem, default="") ).setName("commaSeparatedList")
-
-
-if __name__ == "__main__":
-
-    def test( teststring ):
-        print teststring,"->",
-        try:
-            tokens = simpleSQL.parseString( teststring )
-            tokenlist = tokens.asList()
-            print tokenlist
-            print "tokens = ",        tokens
-            print "tokens.columns =", tokens.columns
-            print "tokens.tables =",  tokens.tables
-            print tokens.asXML("SQL",True)
-        except ParseException, err:
-            print err.line
-            print " "*(err.column-1) + "^"
-            print err
-        print
-
-    selectToken    = CaselessLiteral( "select" )
-    fromToken      = CaselessLiteral( "from" )
-
-    ident          = Word( alphas, alphanums + "_$" )
-    columnName     = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens )
-    columnNameList = Group( delimitedList( columnName ) )#.setName("columns")
-    tableName      = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens )
-    tableNameList  = Group( delimitedList( tableName ) )#.setName("tables")
-    simpleSQL      = ( selectToken + \
-                     ( '*' | columnNameList ).setResultsName( "columns" ) + \
-                     fromToken + \
-                     tableNameList.setResultsName( "tables" ) )
-    
-    test( "SELECT * from XYZZY, ABC" )
-    test( "select * from SYS.XYZZY" )
-    test( "Select A from Sys.dual" )
-    test( "Select AA,BB,CC from Sys.dual" )
-    test( "Select A, B, C from Sys.dual" )
-    test( "Select A, B, C from Sys.dual" )
-    test( "Xelect A, B, C from Sys.dual" )
-    test( "Select A, B, C frox Sys.dual" )
-    test( "Select" )
-    test( "Select ^^^ frox Sys.dual" )
-    test( "Select A, B, C from Sys.dual, Table2   " )
+# module pyparsing.py
+#
+# Copyright (c) 2003-2006  Paul T. McGuire
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+#from __future__ import generators
+
+__doc__ = \
+"""
+pyparsing module - Classes and methods to define and execute parsing grammars
+
+The pyparsing module is an alternative approach to creating and executing simple grammars, 
+vs. the traditional lex/yacc approach, or the use of regular expressions.  With pyparsing, you
+don't need to learn a new syntax for defining grammars or matching expressions - the parsing module 
+provides a library of classes that you use to construct the grammar directly in Python.
+
+Here is a program to parse "Hello, World!" (or any greeting of the form "<salutation>, <addressee>!")::
+
+    from pyparsing import Word, alphas
+    
+    # define grammar of a greeting
+    greet = Word( alphas ) + "," + Word( alphas ) + "!" 
+    
+    hello = "Hello, World!"
+    print hello, "->", greet.parseString( hello )
+
+The program outputs the following::
+
+    Hello, World! -> ['Hello', ',', 'World', '!']
+
+The Python representation of the grammar is quite readable, owing to the self-explanatory 
+class names, and the use of '+', '|' and '^' operators.
+
+The parsed results returned from parseString() can be accessed as a nested list, a dictionary, or an 
+object with named attributes.
+
+The pyparsing module handles some of the problems that are typically vexing when writing text parsers:
+ - extra or missing whitespace (the above program will also handle "Hello,World!", "Hello  ,  World  !", etc.)
+ - quoted strings
+ - embedded comments
+"""
+__version__ = "1.4.5"
+__versionTime__ = "16 December 2006 07:20"
+__author__ = "Paul McGuire <ptmcg@users.sourceforge.net>"
+
+import string
+import copy,sys
+import warnings
+import re
+import sre_constants
+import xml.sax.saxutils
+#~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) )
+
+def _ustr(obj):
+    """Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries
+       str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It
+       then < returns the unicode object | encodes it with the default encoding | ... >.
+    """
+    try:
+        # If this works, then _ustr(obj) has the same behaviour as str(obj), so
+        # it won't break any existing code.
+        return str(obj)
+        
+    except UnicodeEncodeError, e:
+        # The Python docs (http://docs.python.org/ref/customization.html#l2h-182)
+        # state that "The return value must be a string object". However, does a
+        # unicode object (being a subclass of basestring) count as a "string
+        # object"?
+        # If so, then return a unicode object:
+        return unicode(obj)
+        # Else encode it... but how? There are many choices... :)
+        # Replace unprintables with escape codes?
+        #return unicode(obj).encode(sys.getdefaultencoding(), 'backslashreplace_errors')
+        # Replace unprintables with question marks?
+        #return unicode(obj).encode(sys.getdefaultencoding(), 'replace')
+        # ...
+
+def _str2dict(strg):
+    return dict( [(c,0) for c in strg] )
+    #~ return set( [c for c in strg] )
+
+class _Constants(object):
+    pass
+    
+alphas     = string.lowercase + string.uppercase
+nums       = string.digits
+hexnums    = nums + "ABCDEFabcdef"
+alphanums  = alphas + nums    
+
+class ParseBaseException(Exception):
+    """base exception class for all parsing runtime exceptions"""
+    __slots__ = ( "loc","msg","pstr","parserElement" )
+    # Performance tuning: we construct a *lot* of these, so keep this
+    # constructor as small and fast as possible        
+    def __init__( self, pstr, loc, msg, elem=None ):
+        self.loc = loc
+        self.msg = msg
+        self.pstr = pstr
+        self.parserElement = elem
+
+    def __getattr__( self, aname ):
+        """supported attributes by name are:
+            - lineno - returns the line number of the exception text
+            - col - returns the column number of the exception text
+            - line - returns the line containing the exception text
+        """
+        if( aname == "lineno" ):
+            return lineno( self.loc, self.pstr )
+        elif( aname in ("col", "column") ):
+            return col( self.loc, self.pstr )
+        elif( aname == "line" ):
+            return line( self.loc, self.pstr )
+        else:
+            raise AttributeError, aname
+
+    def __str__( self ):
+        return "%s (at char %d), (line:%d, col:%d)" % ( self.msg, self.loc, self.lineno, self.column )
+    def __repr__( self ):
+        return _ustr(self)
+    def markInputline( self, markerString = ">!<" ):
+        """Extracts the exception line from the input string, and marks 
+           the location of the exception with a special symbol.
+        """
+        line_str = self.line
+        line_column = self.column - 1
+        if markerString:
+            line_str = "".join( [line_str[:line_column], markerString, line_str[line_column:]])
+        return line_str.strip()
+
+class ParseException(ParseBaseException):
+    """exception thrown when parse expressions don't match class"""
+    """supported attributes by name are:
+        - lineno - returns the line number of the exception text
+        - col - returns the column number of the exception text
+        - line - returns the line containing the exception text
+    """
+    pass
+    
+class ParseFatalException(ParseBaseException):
+    """user-throwable exception thrown when inconsistent parse content
+       is found; stops all parsing immediately"""
+    pass
+
+class ReparseException(ParseBaseException):
+    def __init_( self, newstring, restartLoc ):
+        self.newParseText = newstring
+        self.reparseLoc = restartLoc
+
+
+class RecursiveGrammarException(Exception):
+    """exception thrown by validate() if the grammar could be improperly recursive"""
+    def __init__( self, parseElementList ):
+        self.parseElementTrace = parseElementList
+    
+    def __str__( self ):
+        return "RecursiveGrammarException: %s" % self.parseElementTrace
+
+class ParseResults(object):
+    """Structured parse results, to provide multiple means of access to the parsed data:
+       - as a list (len(results))
+       - by list index (results[0], results[1], etc.)
+       - by attribute (results.<resultsName>)
+       """
+    __slots__ = ( "__toklist", "__tokdict", "__doinit", "__name", "__parent", "__accumNames" )
+    def __new__(cls, toklist, name=None, asList=True, modal=True ):
+        if isinstance(toklist, cls):
+            return toklist
+        retobj = object.__new__(cls)
+        retobj.__doinit = True
+        return retobj
+        
+    # Performance tuning: we construct a *lot* of these, so keep this
+    # constructor as small and fast as possible
+    def __init__( self, toklist, name=None, asList=True, modal=True ):
+        if self.__doinit:
+            self.__doinit = False
+            self.__name = None
+            self.__parent = None
+            self.__accumNames = {}
+            if isinstance(toklist, list):
+                self.__toklist = toklist[:]
+            else:
+                self.__toklist = [toklist]
+            self.__tokdict = dict()
+
+        # this line is related to debugging the asXML bug
+        #~ asList = False
+        
+        if name:
+            if not modal:
+                self.__accumNames[name] = 0
+            if isinstance(name,int):
+                name = _ustr(name) # will always return a str, but use _ustr for consistency
+            self.__name = name
+            if not toklist in (None,'',[]):
+                if isinstance(toklist,basestring): 
+                    toklist = [ toklist ]
+                if asList:
+                    if isinstance(toklist,ParseResults):
+                        self[name] = (toklist.copy(),-1)
+                    else:
+                        self[name] = (ParseResults(toklist[0]),-1)
+                    self[name].__name = name
+                else:
+                    try:
+                        self[name] = toklist[0]
+                    except (KeyError,TypeError):
+                        self[name] = toklist
+
+    def __getitem__( self, i ):
+        if isinstance( i, (int,slice) ):
+            return self.__toklist[i]
+        else:
+            if i not in self.__accumNames:
+                return self.__tokdict[i][-1][0]
+            else:
+                return ParseResults([ v[0] for v in self.__tokdict[i] ])
+
+    def __setitem__( self, k, v ):
+        if isinstance(v,tuple):
+            self.__tokdict[k] = self.__tokdict.get(k,list()) + [v]
+            sub = v[0]
+        elif isinstance(k,int):
+            self.__toklist[k] = v
+            sub = v
+        else:
+            self.__tokdict[k] = self.__tokdict.get(k,list()) + [(v,0)]
+            sub = v
+        if isinstance(sub,ParseResults):
+            sub.__parent = self
+        
+    def __delitem__( self, i ):
+        if isinstance(i,(int,slice)):
+            del self.__toklist[i]
+        else:
+            del self._tokdict[i]
+
+    def __contains__( self, k ):
+        return self.__tokdict.has_key(k)
+        
+    def __len__( self ): return len( self.__toklist )
+    def __nonzero__( self ): return len( self.__toklist ) > 0
+    def __iter__( self ): return iter( self.__toklist )
+    def keys( self ): 
+        """Returns all named result keys."""
+        return self.__tokdict.keys()
+    
+    def items( self ): 
+        """Returns all named result keys and values as a list of tuples."""
+        return [(k,self[k]) for k in self.__tokdict.keys()]
+    
+    def values( self ): 
+        """Returns all named result values."""
+        return [ v[-1][0] for v in self.__tokdict.values() ]
+
+    def __getattr__( self, name ):
+        if name not in self.__slots__:
+            if self.__tokdict.has_key( name ):
+                if name not in self.__accumNames:
+                    return self.__tokdict[name][-1][0]
+                else:
+                    return ParseResults([ v[0] for v in self.__tokdict[name] ])
+            else:
+                return ""
+        return None
+
+    def __add__( self, other ):
+        ret = self.copy()
+        ret += other
+        return ret
+        
+    def __iadd__( self, other ):
+        if other.__tokdict:
+            offset = len(self.__toklist)
+            addoffset = ( lambda a: (a<0 and offset) or (a+offset) )
+            otheritems = other.__tokdict.items()
+            otherdictitems = [(k,(v[0],addoffset(v[1])) ) for (k,vlist) in otheritems for v in vlist]
+            for k,v in otherdictitems:
+                self[k] = v
+                if isinstance(v[0],ParseResults):
+                    v[0].__parent = self
+        self.__toklist += other.__toklist
+        self.__accumNames.update( other.__accumNames )
+        del other
+        return self
+       
+    def __repr__( self ):
+        return "(%s, %s)" % ( repr( self.__toklist ), repr( self.__tokdict ) )
+
+    def __str__( self ):
+        out = "["
+        sep = ""
+        for i in self.__toklist:
+            if isinstance(i, ParseResults):
+                out += sep + _ustr(i)
+            else:
+                out += sep + repr(i)
+            sep = ", "
+        out += "]"
+        return out
+
+    def _asStringList( self, sep='' ):
+        out = []
+        for item in self.__toklist:
+            if out and sep:
+                out.append(sep)
+            if isinstance( item, ParseResults ):
+                out += item._asStringList()
+            else:
+                out.append( _ustr(item) )
+        return out
+
+    def asList( self ):
+        """Returns the parse results as a nested list of matching tokens, all converted to strings."""
+        out = []
+        for res in self.__toklist:
+            if isinstance(res,ParseResults):
+                out.append( res.asList() )
+            else:
+                out.append( res )
+        return out
+
+    def asDict( self ):
+        """Returns the named parse results as dictionary."""
+        return dict( self.items() )
+
+    def copy( self ):
+        """Returns a new copy of a ParseResults object."""
+        ret = ParseResults( self.__toklist )
+        ret.__tokdict = self.__tokdict.copy()
+        ret.__parent = self.__parent
+        ret.__accumNames.update( self.__accumNames )
+        ret.__name = self.__name
+        return ret
+        
+    def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
+        """Returns the parse results as XML. Tags are created for tokens and lists that have defined results names."""
+        nl = "\n"
+        out = []
+        namedItems = dict( [ (v[1],k) for (k,vlist) in self.__tokdict.items() for v in vlist ] )
+        nextLevelIndent = indent + "  "
+        
+        # collapse out indents if formatting is not desired
+        if not formatted:
+            indent = ""
+            nextLevelIndent = ""
+            nl = ""
+            
+        selfTag = None
+        if doctag is not None:
+            selfTag = doctag
+        else:
+            if self.__name:
+                selfTag = self.__name
+        
+        if not selfTag:
+            if namedItemsOnly:
+                return ""
+            else:
+                selfTag = "ITEM"
+        
+        out += [ nl, indent, "<", selfTag, ">" ]
+        
+        worklist = self.__toklist
+        for i,res in enumerate(worklist):
+            if isinstance(res,ParseResults):
+                if i in namedItems:
+                    out += [ res.asXML(namedItems[i], namedItemsOnly and doctag is None, nextLevelIndent,formatted)]
+                else:
+                    out += [ res.asXML(None, namedItemsOnly and doctag is None, nextLevelIndent,formatted)]
+            else:
+                # individual token, see if there is a name for it
+                resTag = None
+                if i in namedItems:
+                    resTag = namedItems[i]
+                if not resTag:
+                    if namedItemsOnly:
+                        continue
+                    else:
+                        resTag = "ITEM"
+                xmlBodyText = xml.sax.saxutils.escape(_ustr(res))
+                out += [ nl, nextLevelIndent, "<", resTag, ">", xmlBodyText, "</", resTag, ">" ]
+        
+        out += [ nl, indent, "</", selfTag, ">" ]
+        return "".join(out)
+
+    def __lookup(self,sub):
+        for k,vlist in self.__tokdict.items():
+            for v,loc in vlist:
+                if sub is v:
+                    return k
+        return None
+            
+    def getName(self):
+        """Returns the results name for this token expression."""
+        if self.__name:
+            return self.__name
+        elif self.__parent:
+            par = self.__parent
+            if par:
+                return par.__lookup(self)
+            else:
+                return None
+        elif (len(self) == 1 and 
+               len(self.__tokdict) == 1 and
+               self.__tokdict.values()[0][0][1] in (0,-1)):
+            return self.__tokdict.keys()[0]
+        else:
+            return None
+            
+    def dump(self,indent='',depth=0):
+        """Diagnostic method for listing out the contents of a ParseResults.
+           Accepts an optional indent argument so that this string can be embedded
+           in a nested display of other data."""
+        out = []
+        out.append( indent+str(self.asList()) )
+        keys = self.items()
+        keys.sort()
+        for k,v in keys:
+            if out:
+                out.append('\n')
+            out.append( "%s%s- %s: " % (indent,('  '*depth), k) )
+            if isinstance(v,ParseResults):
+                if v.keys():
+                    #~ out.append('\n')
+                    out.append( v.dump(indent,depth+1) )
+                    #~ out.append('\n')
+                else:
+                    out.append(str(v))
+            else:
+                out.append(str(v))
+        #~ out.append('\n')
+        return "".join(out)
+
+    # add support for pickle protocol
+    def __getstate__(self):
+        return ( self.__toklist,
+                 ( self.__tokdict.copy(),
+                   self.__parent,
+                   self.__accumNames,
+                   self.__name ) )
+    
+    def __setstate__(self,state):
+        self.__toklist = state[0]
+        self.__tokdict, \
+        self.__parent, \
+        inAccumNames, \
+        self.__name = state[1]
+        self.__accumNames = {}
+        self.__accumNames.update(inAccumNames)
+
+
+def col (loc,strg):
+    """Returns current column within a string, counting newlines as line separators.
+   The first column is number 1.
+   """
+    return (loc<len(strg) and strg[loc] == '\n') and 1 or loc - strg.rfind("\n", 0, loc)
+
+def lineno(loc,strg):
+    """Returns current line number within a string, counting newlines as line separators.
+   The first line is number 1.
+   """
+    return strg.count("\n",0,loc) + 1
+
+def line( loc, strg ):
+    """Returns the line of text containing loc within a string, counting newlines as line separators.
+       """
+    lastCR = strg.rfind("\n", 0, loc)
+    nextCR = strg.find("\n", loc)
+    if nextCR > 0:
+        return strg[lastCR+1:nextCR]
+    else:
+        return strg[lastCR+1:]
+
+def _defaultStartDebugAction( instring, loc, expr ):
+    print "Match",expr,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )
+
+def _defaultSuccessDebugAction( instring, startloc, endloc, expr, toks ):
+    print "Matched",expr,"->",toks.asList()
+    
+def _defaultExceptionDebugAction( instring, loc, expr, exc ):
+    print "Exception raised:", exc
+
+def nullDebugAction(*args):
+    """'Do-nothing' debug action, to suppress debugging output during parsing."""
+    pass
+
+class ParserElement(object):
+    """Abstract base level parser element class."""
+    DEFAULT_WHITE_CHARS = " \n\t\r"
+    
+    def setDefaultWhitespaceChars( chars ):
+        """Overrides the default whitespace chars
+        """
+        ParserElement.DEFAULT_WHITE_CHARS = chars
+    setDefaultWhitespaceChars = staticmethod(setDefaultWhitespaceChars)
+    
+    def __init__( self, savelist=False ):
+        self.parseAction = list()
+        self.failAction = None
+        #~ self.name = "<unknown>"  # don't define self.name, let subclasses try/except upcall
+        self.strRepr = None
+        self.resultsName = None
+        self.saveAsList = savelist
+        self.skipWhitespace = True
+        self.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
+        self.copyDefaultWhiteChars = True
+        self.mayReturnEmpty = False
+        self.keepTabs = False
+        self.ignoreExprs = list()
+        self.debug = False
+        self.streamlined = False
+        self.mayIndexError = True
+        self.errmsg = ""
+        self.modalResults = True
+        self.debugActions = ( None, None, None )
+        self.re = None
+
+    def copy( self ):
+        """Make a copy of this ParserElement.  Useful for defining different parse actions
+           for the same parsing pattern, using copies of the original parse element."""
+        cpy = copy.copy( self )
+        cpy.parseAction = self.parseAction[:]
+        cpy.ignoreExprs = self.ignoreExprs[:]
+        if self.copyDefaultWhiteChars:
+            cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
+        return cpy
+
+    def setName( self, name ):
+        """Define name for this expression, for use in debugging."""
+        self.name = name
+        self.errmsg = "Expected " + self.name
+        return self
+
+    def setResultsName( self, name, listAllMatches=False ):
+        """Define name for referencing matching tokens as a nested attribute 
+           of the returned parse results.
+           NOTE: this returns a *copy* of the original ParserElement object;
+           this is so that the client can define a basic element, such as an
+           integer, and reference it in multiple places with different names.
+        """
+        newself = self.copy()
+        newself.resultsName = name
+        newself.modalResults = not listAllMatches
+        return newself
+
+    def normalizeParseActionArgs( f ):
+        """Internal method used to decorate parse actions that take fewer than 3 arguments,
+           so that all parse actions can be called as f(s,l,t)."""
+        STAR_ARGS = 4
+
+        try:
+            restore = None
+            if isinstance(f,type):
+                restore = f
+                f = f.__init__
+            if f.func_code.co_flags & STAR_ARGS:
+                return f
+            numargs = f.func_code.co_argcount
+            if hasattr(f,"im_self"):
+                numargs -= 1
+            if restore:
+                f = restore
+        except AttributeError:
+            try:
+                # not a function, must be a callable object, get info from the
+                # im_func binding of its bound __call__ method
+                if f.__call__.im_func.func_code.co_flags & STAR_ARGS:
+                    return f
+                numargs = f.__call__.im_func.func_code.co_argcount
+                if hasattr(f.__call__,"im_self"):
+                    numargs -= 1
+            except AttributeError:
+                # not a bound method, get info directly from __call__ method
+                if f.__call__.func_code.co_flags & STAR_ARGS:
+                    return f
+                numargs = f.__call__.func_code.co_argcount
+                if hasattr(f.__call__,"im_self"):
+                    numargs -= 1
+
+        #~ print "adding function %s with %d args" % (f.func_name,numargs)
+        if numargs == 3:
+            return f
+        else:
+            if numargs == 2:
+                def tmp(s,l,t):
+                    return f(l,t)
+            elif numargs == 1:
+                def tmp(s,l,t):
+                    return f(t)
+            else: #~ numargs == 0:
+                def tmp(s,l,t):
+                    return f()
+            return tmp
+    normalizeParseActionArgs = staticmethod(normalizeParseActionArgs)
+            
+    def setParseAction( self, *fns ):
+        """Define action to perform when successfully matching parse element definition.
+           Parse action fn is a callable method with 0-3 arguments, called as fn(s,loc,toks),
+           fn(loc,toks), fn(toks), or just fn(), where:
+            - s   = the original string being parsed
+            - loc = the location of the matching substring
+            - toks = a list of the matched tokens, packaged as a ParseResults object
+           If the functions in fns modify the tokens, they can return them as the return
+           value from fn, and the modified list of tokens will replace the original.
+           Otherwise, fn does not need to return any value."""
+        self.parseAction = map(self.normalizeParseActionArgs, list(fns))
+        return self
+
+    def addParseAction( self, *fns ):
+        """Add parse action to expression's list of parse actions. See setParseAction_."""
+        self.parseAction += map(self.normalizeParseActionArgs, list(fns))
+        return self
+
+    def setFailAction( self, fn ):
+        """Define action to perform if parsing fails at this expression. 
+           Fail acton fn is a callable function that takes the arguments 
+           fn(s,loc,expr,err) where:
+            - s = string being parsed
+            - loc = location where expression match was attempted and failed
+            - expr = the parse expression that failed
+            - err = the exception thrown
+           The function returns no value.  It may throw ParseFatalException
+           if it is desired to stop parsing immediately."""
+        self.failAction = fn
+        return self
+        
+    def skipIgnorables( self, instring, loc ):
+        exprsFound = True
+        while exprsFound:
+            exprsFound = False
+            for e in self.ignoreExprs:
+                try:
+                    while 1:
+                        loc,dummy = e._parse( instring, loc )
+                        exprsFound = True
+                except ParseException:
+                    pass
+        return loc
+
+    def preParse( self, instring, loc ):
+        if self.ignoreExprs:
+            loc = self.skipIgnorables( instring, loc )
+        
+        if self.skipWhitespace:
+            wt = self.whiteChars
+            instrlen = len(instring)
+            while loc < instrlen and instring[loc] in wt:
+                loc += 1
+                
+        return loc
+
+    def parseImpl( self, instring, loc, doActions=True ):
+        return loc, []
+
+    def postParse( self, instring, loc, tokenlist ):
+        return tokenlist
+
+    #~ @profile
+    def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ):
+        debugging = ( self.debug ) #and doActions )
+
+        if debugging or self.failAction:
+            #~ print "Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )
+            if (self.debugActions[0] ):
+                self.debugActions[0]( instring, loc, self )
+            if callPreParse:
+                preloc = self.preParse( instring, loc )
+            else:
+                preloc = loc
+            tokensStart = loc
+            try:
+                try:
+                    loc,tokens = self.parseImpl( instring, preloc, doActions )
+                except IndexError:
+                    raise ParseException( instring, len(instring), self.errmsg, self )
+            #~ except ReparseException, retryEx:
+                #~ pass
+            except ParseException, err:
+                #~ print "Exception raised:", err
+                if self.debugActions[2]:
+                    self.debugActions[2]( instring, tokensStart, self, err )
+                if self.failAction:
+                    self.failAction( instring, tokensStart, self, err )
+                raise
+        else:
+            if callPreParse:
+                preloc = self.preParse( instring, loc )
+            else:
+                preloc = loc
+            tokensStart = loc
+            if self.mayIndexError or loc >= len(instring):
+                try:
+                    loc,tokens = self.parseImpl( instring, preloc, doActions )
+                except IndexError:
+                    raise ParseException( instring, len(instring), self.errmsg, self )
+            else:
+                loc,tokens = self.parseImpl( instring, preloc, doActions )
+        
+        tokens = self.postParse( instring, loc, tokens )
+
+        retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults )
+        if self.parseAction and doActions:
+            if debugging:
+                try:
+                    for fn in self.parseAction:
+                        tokens = fn( instring, tokensStart, retTokens )
+                        if tokens is not None:
+                            retTokens = ParseResults( tokens, 
+                                                      self.resultsName, 
+                                                      asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), 
+                                                      modal=self.modalResults )
+                except ParseException, err:
+                    #~ print "Exception raised in user parse action:", err
+                    if (self.debugActions[2] ):
+                        self.debugActions[2]( instring, tokensStart, self, err )
+                    raise
+            else:
+                for fn in self.parseAction:
+                    tokens = fn( instring, tokensStart, retTokens )
+                    if tokens is not None:
+                        retTokens = ParseResults( tokens, 
+                                                  self.resultsName, 
+                                                  asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), 
+                                                  modal=self.modalResults )
+
+        if debugging:
+            #~ print "Matched",self,"->",retTokens.asList()
+            if (self.debugActions[1] ):
+                self.debugActions[1]( instring, tokensStart, loc, self, retTokens )
+
+        return loc, retTokens
+
+    def tryParse( self, instring, loc ):
+        return self._parse( instring, loc, doActions=False )[0]
+    
+    # this method gets repeatedly called during backtracking with the same arguments -
+    # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression
+    def _parseCache( self, instring, loc, doActions=True, callPreParse=True ):
+        if doActions and self.parseAction:
+            return self._parseNoCache( instring, loc, doActions, callPreParse )
+        lookup = (self,instring,loc,callPreParse)
+        if lookup in ParserElement._exprArgCache:
+            value = ParserElement._exprArgCache[ lookup ]
+            if isinstance(value,Exception):
+                if isinstance(value,ParseBaseException):
+                    value.loc = loc
+                raise value
+            return value
+        else:
+            try:
+                ParserElement._exprArgCache[ lookup ] = \
+                    value = self._parseNoCache( instring, loc, doActions, callPreParse )
+                return value
+            except ParseBaseException, pe:
+                ParserElement._exprArgCache[ lookup ] = pe
+                raise
+
+    _parse = _parseNoCache
+
+    # argument cache for optimizing repeated calls when backtracking through recursive expressions
+    _exprArgCache = {}
+    def resetCache():
+        ParserElement._exprArgCache.clear()
+    resetCache = staticmethod(resetCache)
+    
+    _packratEnabled = False
+    def enablePackrat():
+        """Enables "packrat" parsing, which adds memoizing to the parsing logic.
+           Repeated parse attempts at the same string location (which happens 
+           often in many complex grammars) can immediately return a cached value, 
+           instead of re-executing parsing/validating code.  Memoizing is done of
+           both valid results and parsing exceptions.
+            
+           This speedup may break existing programs that use parse actions that 
+           have side-effects.  For this reason, packrat parsing is disabled when
+           you first import pyparsing.  To activate the packrat feature, your
+           program must call the class method ParserElement.enablePackrat().  If
+           your program uses psyco to "compile as you go", you must call 
+           enablePackrat before calling psyco.full().  If you do not do this,
+           Python will crash.  For best results, call enablePackrat() immediately
+           after importing pyparsing.
+        """
+        if not ParserElement._packratEnabled:
+            ParserElement._packratEnabled = True
+            ParserElement._parse = ParserElement._parseCache
+    enablePackrat = staticmethod(enablePackrat)
+
+    def parseString( self, instring ):
+        """Execute the parse expression with the given string.
+           This is the main interface to the client code, once the complete 
+           expression has been built.
+        """
+        ParserElement.resetCache()
+        if not self.streamlined:
+            self.streamline()
+            #~ self.saveAsList = True
+        for e in self.ignoreExprs:
+            e.streamline()
+        if self.keepTabs:
+            loc, tokens = self._parse( instring, 0 )
+        else:
+            loc, tokens = self._parse( instring.expandtabs(), 0 )
+        return tokens
+
+    def scanString( self, instring, maxMatches=sys.maxint ):
+        """Scan the input string for expression matches.  Each match will return the 
+           matching tokens, start location, and end location.  May be called with optional
+           maxMatches argument, to clip scanning after 'n' matches are found."""
+        if not self.streamlined:
+            self.streamline()
+        for e in self.ignoreExprs:
+            e.streamline()
+        
+        if not self.keepTabs:
+            instring = instring.expandtabs()
+        instrlen = len(instring)
+        loc = 0
+        preparseFn = self.preParse
+        parseFn = self._parse
+        ParserElement.resetCache()
+        matches = 0
+        while loc <= instrlen and matches < maxMatches:
+            try:
+                preloc = preparseFn( instring, loc )
+                nextLoc,tokens = parseFn( instring, preloc, callPreParse=False )
+            except ParseException:
+                loc = preloc+1
+            else:
+                matches += 1
+                yield tokens, preloc, nextLoc
+                loc = nextLoc
+        
+    def transformString( self, instring ):
+        """Extension to scanString, to modify matching text with modified tokens that may
+           be returned from a parse action.  To use transformString, define a grammar and 
+           attach a parse action to it that modifies the returned token list.  
+           Invoking transformString() on a target string will then scan for matches, 
+           and replace the matched text patterns according to the logic in the parse 
+           action.  transformString() returns the resulting transformed string."""
+        out = []
+        lastE = 0
+        # force preservation of <TAB>s, to minimize unwanted transformation of string, and to
+        # keep string locs straight between transformString and scanString
+        self.keepTabs = True
+        for t,s,e in self.scanString( instring ):
+            out.append( instring[lastE:s] )
+            if t:
+                if isinstance(t,ParseResults):
+                    out += t.asList()
+                elif isinstance(t,list):
+                    out += t
+                else:
+                    out.append(t)
+            lastE = e
+        out.append(instring[lastE:])
+        return "".join(out)
+
+    def searchString( self, instring, maxMatches=sys.maxint ):
+        """Another extension to scanString, simplifying the access to the tokens found
+           to match the given parse expression.  May be called with optional
+           maxMatches argument, to clip searching after 'n' matches are found.
+        """
+        return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ])
+            
+    def __add__(self, other ):
+        """Implementation of + operator - returns And"""
+        if isinstance( other, basestring ):
+            other = Literal( other )
+        if not isinstance( other, ParserElement ):
+            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+                    SyntaxWarning, stacklevel=2)
+        return And( [ self, other ] )
+
+    def __radd__(self, other ):
+        """Implementation of += operator"""
+        if isinstance( other, basestring ):
+            other = Literal( other )
+        if not isinstance( other, ParserElement ):
+            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+                    SyntaxWarning, stacklevel=2)
+        return other + self
+
+    def __or__(self, other ):
+        """Implementation of | operator - returns MatchFirst"""
+        if isinstance( other, basestring ):
+            other = Literal( other )
+        if not isinstance( other, ParserElement ):
+            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+                    SyntaxWarning, stacklevel=2)
+        return MatchFirst( [ self, other ] )
+
+    def __ror__(self, other ):
+        """Implementation of |= operator"""
+        if isinstance( other, basestring ):
+            other = Literal( other )
+        if not isinstance( other, ParserElement ):
+            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+                    SyntaxWarning, stacklevel=2)
+        return other | self
+
+    def __xor__(self, other ):
+        """Implementation of ^ operator - returns Or"""
+        if isinstance( other, basestring ):
+            other = Literal( other )
+        if not isinstance( other, ParserElement ):
+            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+                    SyntaxWarning, stacklevel=2)
+        return Or( [ self, other ] )
+
+    def __rxor__(self, other ):
+        """Implementation of ^= operator"""
+        if isinstance( other, basestring ):
+            other = Literal( other )
+        if not isinstance( other, ParserElement ):
+            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+                    SyntaxWarning, stacklevel=2)
+        return other ^ self
+
+    def __and__(self, other ):
+        """Implementation of & operator - returns Each"""
+        if isinstance( other, basestring ):
+            other = Literal( other )
+        if not isinstance( other, ParserElement ):
+            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+                    SyntaxWarning, stacklevel=2)
+        return Each( [ self, other ] )
+
+    def __rand__(self, other ):
+        """Implementation of right-& operator"""
+        if isinstance( other, basestring ):
+            other = Literal( other )
+        if not isinstance( other, ParserElement ):
+            warnings.warn("Cannot add element of type %s to ParserElement" % type(other),
+                    SyntaxWarning, stacklevel=2)
+        return other & self
+
+    def __invert__( self ):
+        """Implementation of ~ operator - returns NotAny"""
+        return NotAny( self )
+
+    def suppress( self ):
+        """Suppresses the output of this ParserElement; useful to keep punctuation from
+           cluttering up returned output.
+        """
+        return Suppress( self )
+
+    def leaveWhitespace( self ):
+        """Disables the skipping of whitespace before matching the characters in the 
+           ParserElement's defined pattern.  This is normally only used internally by
+           the pyparsing module, but may be needed in some whitespace-sensitive grammars.
+        """
+        self.skipWhitespace = False
+        return self
+
+    def setWhitespaceChars( self, chars ):
+        """Overrides the default whitespace chars
+        """
+        self.skipWhitespace = True
+        self.whiteChars = chars
+        self.copyDefaultWhiteChars = False
+        return self
+        
+    def parseWithTabs( self ):
+        """Overrides default behavior to expand <TAB>s to spaces before parsing the input string.
+           Must be called before parseString when the input grammar contains elements that 
+           match <TAB> characters."""
+        self.keepTabs = True
+        return self
+        
+    def ignore( self, other ):
+        """Define expression to be ignored (e.g., comments) while doing pattern 
+           matching; may be called repeatedly, to define multiple comment or other
+           ignorable patterns.
+        """
+        if isinstance( other, Suppress ):
+            if other not in self.ignoreExprs:
+                self.ignoreExprs.append( other )
+        else:
+            self.ignoreExprs.append( Suppress( other ) )
+        return self
+
+    def setDebugActions( self, startAction, successAction, exceptionAction ):
+        """Enable display of debugging messages while doing pattern matching."""
+        self.debugActions = (startAction or _defaultStartDebugAction, 
+                             successAction or _defaultSuccessDebugAction, 
+                             exceptionAction or _defaultExceptionDebugAction)
+        self.debug = True
+        return self
+
+    def setDebug( self, flag=True ):
+        """Enable display of debugging messages while doing pattern matching."""
+        if flag:
+            self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )
+        else:
+            self.debug = False
+        return self
+
+    def __str__( self ):
+        return self.name
+
+    def __repr__( self ):
+        return _ustr(self)
+        
+    def streamline( self ):
+        self.streamlined = True
+        self.strRepr = None
+        return self
+        
+    def checkRecursion( self, parseElementList ):
+        pass
+        
+    def validate( self, validateTrace=[] ):
+        """Check defined expressions for valid structure, check for infinite recursive definitions."""
+        self.checkRecursion( [] )
+
+    def parseFile( self, file_or_filename ):
+        """Execute the parse expression on the given file or filename.
+           If a filename is specified (instead of a file object),
+           the entire file is opened, read, and closed before parsing.
+        """
+        try:
+            file_contents = file_or_filename.read()
+        except AttributeError:
+            f = open(file_or_filename, "rb")
+            file_contents = f.read()
+            f.close()
+        return self.parseString(file_contents)
+
+
+class Token(ParserElement):
+    """Abstract ParserElement subclass, for defining atomic matching patterns."""
+    def __init__( self ):
+        super(Token,self).__init__( savelist=False )
+        self.myException = ParseException("",0,"",self)
+
+    def setName(self, name):
+        s = super(Token,self).setName(name)
+        self.errmsg = "Expected " + self.name
+        s.myException.msg = self.errmsg
+        return s
+
+
+class Empty(Token):
+    """An empty token, will always match."""
+    def __init__( self ):
+        super(Empty,self).__init__()
+        self.name = "Empty"
+        self.mayReturnEmpty = True
+        self.mayIndexError = False
+
+
+class NoMatch(Token):
+    """A token that will never match."""
+    def __init__( self ):
+        super(NoMatch,self).__init__()
+        self.name = "NoMatch"
+        self.mayReturnEmpty = True
+        self.mayIndexError = False
+        self.errmsg = "Unmatchable token"
+        self.myException.msg = self.errmsg
+        
+    def parseImpl( self, instring, loc, doActions=True ):
+        exc = self.myException
+        exc.loc = loc
+        exc.pstr = instring
+        raise exc
+
+
+class Literal(Token):
+    """Token to exactly match a specified string."""
+    def __init__( self, matchString ):
+        super(Literal,self).__init__()
+        self.match = matchString
+        self.matchLen = len(matchString)
+        try:
+            self.firstMatchChar = matchString[0]
+        except IndexError:
+            warnings.warn("null string passed to Literal; use Empty() instead", 
+                            SyntaxWarning, stacklevel=2)
+            self.__class__ = Empty
+        self.name = '"%s"' % self.match
+        self.errmsg = "Expected " + self.name
+        self.mayReturnEmpty = False
+        self.myException.msg = self.errmsg
+        self.mayIndexError = False
+
+    # Performance tuning: this routine gets called a *lot*
+    # if this is a single character match string  and the first character matches,
+    # short-circuit as quickly as possible, and avoid calling startswith
+    #~ @profile
+    def parseImpl( self, instring, loc, doActions=True ):
+        if (instring[loc] == self.firstMatchChar and
+            (self.matchLen==1 or instring.startswith(self.match,loc)) ):
+            return loc+self.matchLen, self.match
+        #~ raise ParseException( instring, loc, self.errmsg )
+        exc = self.myException
+        exc.loc = loc
+        exc.pstr = instring
+        raise exc
+
+class Keyword(Token):
+    """Token to exactly match a specified string as a keyword, that is, it must be 
+       immediately followed by a non-keyword character.  Compare with Literal::
+         Literal("if") will match the leading 'if' in 'ifAndOnlyIf'.
+         Keyword("if") will not; it will only match the leading 'if in 'if x=1', or 'if(y==2)'
+       Accepts two optional constructor arguments in addition to the keyword string:
+       identChars is a string of characters that would be valid identifier characters,
+       defaulting to all alphanumerics + "_" and "$"; caseless allows case-insensitive
+       matching, default is False.
+    """
+    DEFAULT_KEYWORD_CHARS = alphanums+"_$"
+    
+    def __init__( self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False ):
+        super(Keyword,self).__init__()
+        self.match = matchString
+        self.matchLen = len(matchString)
+        try:
+            self.firstMatchChar = matchString[0]
+        except IndexError:
+            warnings.warn("null string passed to Keyword; use Empty() instead", 
+                            SyntaxWarning, stacklevel=2)
+        self.name = '"%s"' % self.match
+        self.errmsg = "Expected " + self.name
+        self.mayReturnEmpty = False
+        self.myException.msg = self.errmsg
+        self.mayIndexError = False
+        self.caseless = caseless
+        if caseless:
+            self.caselessmatch = matchString.upper()
+            identChars = identChars.upper()
+        self.identChars = _str2dict(identChars)
+
+    def parseImpl( self, instring, loc, doActions=True ):
+        if self.caseless:
+            if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
+                 (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) and
+                 (loc == 0 or instring[loc-1].upper() not in self.identChars) ):
+                return loc+self.matchLen, self.match
+        else:
+            if (instring[loc] == self.firstMatchChar and
+                (self.matchLen==1 or instring.startswith(self.match,loc)) and
+                (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen] not in self.identChars) and
+                (loc == 0 or instring[loc-1] not in self.identChars) ):
+                return loc+self.matchLen, self.match
+        #~ raise ParseException( instring, loc, self.errmsg )
+        exc = self.myException
+        exc.loc = loc
+        exc.pstr = instring
+        raise exc
+        
+    def copy(self):
+        c = super(Keyword,self).copy()
+        c.identChars = Keyword.DEFAULT_KEYWORD_CHARS
+        return c
+        
+    def setDefaultKeywordChars( chars ):
+        """Overrides the default Keyword chars
+        """
+        Keyword.DEFAULT_KEYWORD_CHARS = chars
+    setDefaultKeywordChars = staticmethod(setDefaultKeywordChars)        
+
+
+class CaselessLiteral(Literal):
+    """Token to match a specified string, ignoring case of letters.
+       Note: the matched results will always be in the case of the given
+       match string, NOT the case of the input text.
+    """
+    def __init__( self, matchString ):
+        super(CaselessLiteral,self).__init__( matchString.upper() )
+        # Preserve the defining literal.
+        self.returnString = matchString
+        self.name = "'%s'" % self.returnString
+        self.errmsg = "Expected " + self.name
+        self.myException.msg = self.errmsg
+
+    def parseImpl( self, instring, loc, doActions=True ):
+        if instring[ loc:loc+self.matchLen ].upper() == self.match:
+            return loc+self.matchLen, self.returnString
+        #~ raise ParseException( instring, loc, self.errmsg )
+        exc = self.myException
+        exc.loc = loc
+        exc.pstr = instring
+        raise exc
+
+class CaselessKeyword(Keyword):
+    def __init__( self, matchString, identChars=Keyword.DEFAULT_KEYWORD_CHARS ):
+        super(CaselessKeyword,self).__init__( matchString, identChars, caseless=True )
+
+    def parseImpl( self, instring, loc, doActions=True ):
+        if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
+             (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) ):
+            return loc+self.matchLen, self.match
+        #~ raise ParseException( instring, loc, self.errmsg )
+        exc = self.myException
+        exc.loc = loc
+        exc.pstr = instring
+        raise exc
+
+class Word(Token):
+    """Token for matching words composed of allowed character sets.
+       Defined with string containing all allowed initial characters,
+       an optional string containing allowed body characters (if omitted,
+       defaults to the initial character set), and an optional minimum,
+       maximum, and/or exact length.
+    """
+    def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0 ):
+        super(Word,self).__init__()
+        self.initCharsOrig = initChars
+        self.initChars = _str2dict(initChars)
+        if bodyChars :
+            self.bodyCharsOrig = bodyChars
+            self.bodyChars = _str2dict(bodyChars)
+        else:
+            self.bodyCharsOrig = initChars
+            self.bodyChars = _str2dict(initChars)
+            
+        self.maxSpecified = max > 0
+
+        self.minLen = min
+
+        if max > 0:
+            self.maxLen = max
+        else:
+            self.maxLen = sys.maxint
+
+        if exact > 0:
+            self.maxLen = exact
+            self.minLen = exact
+
+        self.name = _ustr(self)
+        self.errmsg = "Expected " + self.name
+        self.myException.msg = self.errmsg
+        self.mayIndexError = False
+        
+        if ' ' not in self.initCharsOrig+self.bodyCharsOrig and (min==1 and max==0 and exact==0):
+            if self.bodyCharsOrig == self.initCharsOrig:
+                self.reString = "[%s]+" % _escapeRegexRangeChars(self.initCharsOrig)
+            elif len(self.bodyCharsOrig) == 1:
+                self.reString = "%s[%s]*" % \
+                                      (re.escape(self.initCharsOrig),
+                                      _escapeRegexRangeChars(self.bodyCharsOrig),)
+            else:
+                self.reString = "[%s][%s]*" % \
+                                      (_escapeRegexRangeChars(self.initCharsOrig),
+                                      _escapeRegexRangeChars(self.bodyCharsOrig),)
+            try:
+                self.re = re.compile( self.reString )
+            except:
+                self.re = None
+        
+    def parseImpl( self, instring, loc, doActions=True ):
+        if self.re:
+            result = self.re.match(instring,loc)
+            if not result:
+                exc = self.myException
+                exc.loc = loc
+                exc.pstr = instring
+                raise exc
+            
+            loc = result.end()
+            return loc,result.group()
+        
+        if not(instring[ loc ] in self.initChars):
+            #~ raise ParseException( instring, loc, self.errmsg )
+            exc = self.myException
+            exc.loc = loc
+            exc.pstr = instring
+            raise exc
+        start = loc
+        loc += 1
+        instrlen = len(instring)
+        bodychars = self.bodyChars
+        maxloc = start + self.maxLen
+        maxloc = min( maxloc, instrlen )
+        while loc < maxloc and instring[loc] in bodychars:
+            loc += 1
+            
+        throwException = False
+        if loc - start < self.minLen:
+            throwException = True
+        if self.maxSpecified and loc < instrlen and instring[loc] in bodychars:
+            throwException = True
+
+        if throwException:
+            #~ raise ParseException( instring, loc, self.errmsg )
+            exc = self.myException
+            exc.loc = loc
+            exc.pstr = instring
+            raise exc
+
+        return loc, instring[start:loc]
+
+    def __str__( self ):
+        try:
+            return super(Word,self).__str__()
+        except:
+            pass
+
+            
+        if self.strRepr is None:
+            
+            def charsAsStr(s):
+                if len(s)>4:
+                    return s[:4]+"..."
+                else:
+                    return s
+            
+            if ( self.initCharsOrig != self.bodyCharsOrig ):
+                self.strRepr = "W:(%s,%s)" % ( charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig) )
+            else:
+                self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig)
+
+        return self.strRepr
+
+
+class Regex(Token):
+    """Token for matching strings that match a given regular expression.
+       Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module.
+    """
+    def __init__( self, pattern, flags=0):
+        """The parameters pattern and flags are passed to the re.compile() function as-is. See the Python re module for an explanation of the acceptable patterns and flags."""
+        super(Regex,self).__init__()
+        
+        if len(pattern) == 0:
+            warnings.warn("null string passed to Regex; use Empty() instead", 
+                    SyntaxWarning, stacklevel=2)
+    
+        self.pattern = pattern
+        self.flags = flags
+        
+        try:
+            self.re = re.compile(self.pattern, self.flags)
+            self.reString = self.pattern
+        except sre_constants.error,e:
+            warnings.warn("invalid pattern (%s) passed to Regex" % pattern, 
+                SyntaxWarning, stacklevel=2)
+            raise
+
+        self.name = _ustr(self)
+        self.errmsg = "Expected " + self.name
+        self.myException.msg = self.errmsg
+        self.mayIndexError = False
+        self.mayReturnEmpty = True
+    
+    def parseImpl( self, instring, loc, doActions=True ):
+        result = self.re.match(instring,loc)
+        if not result:
+            exc = self.myException
+            exc.loc = loc
+            exc.pstr = instring
+            raise exc
+        
+        loc = result.end()
+        d = result.groupdict()
+        ret = ParseResults(result.group())
+        if d:
+            for k in d.keys():
+                ret[k] = d[k]
+        return loc,ret
+    
+    def __str__( self ):
+        try:
+            return super(Regex,self).__str__()
+        except:
+            pass
+        
+        if self.strRepr is None:
+            self.strRepr = "Re:(%s)" % repr(self.pattern)
+        
+        return self.strRepr
+
+
+class QuotedString(Token):
+    """Token for matching strings that are delimited by quoting characters.
+    """
+    def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None):
+        """
+           Defined with the following parameters:
+           - quoteChar - string of one or more characters defining the quote delimiting string
+           - escChar - character to escape quotes, typically backslash (default=None)
+           - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=None)
+           - multiline - boolean indicating whether quotes can span multiple lines (default=False)
+           - unquoteResults - boolean indicating whether the matched text should be unquoted (default=True)
+           - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=None => same as quoteChar)
+        """
+        super(QuotedString,self).__init__()
+        
+        # remove white space from quote chars - wont work anyway
+        quoteChar = quoteChar.strip()
+        if len(quoteChar) == 0:
+            warnings.warn("quoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
+            raise SyntaxError()
+        
+        if endQuoteChar is None:
+            endQuoteChar = quoteChar
+        else:
+            endQuoteChar = endQuoteChar.strip()
+            if len(endQuoteChar) == 0:
+                warnings.warn("endQuoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
+                raise SyntaxError()
+        
+        self.quoteChar = quoteChar
+        self.quoteCharLen = len(quoteChar)
+        self.firstQuoteChar = quoteChar[0]
+        self.endQuoteChar = endQuoteChar
+        self.endQuoteCharLen = len(endQuoteChar)
+        self.escChar = escChar
+        self.escQuote = escQuote
+        self.unquoteResults = unquoteResults
+        
+        if multiline:
+            self.flags = re.MULTILINE | re.DOTALL
+            self.pattern = r'%s(?:[^%s%s]' % \
+                ( re.escape(self.quoteChar),
+                  _escapeRegexRangeChars(self.endQuoteChar[0]),
+                  (escChar is not None and _escapeRegexRangeChars(escChar) or '') )
+        else:
+            self.flags = 0
+            self.pattern = r'%s(?:[^%s\n\r%s]' % \
+                ( re.escape(self.quoteChar),
+                  _escapeRegexRangeChars(self.endQuoteChar[0]),
+                  (escChar is not None and _escapeRegexRangeChars(escChar) or '') )
+        if len(self.endQuoteChar) > 1:
+            self.pattern += (
+                '|(?:' + ')|(?:'.join(["%s[^%s]" % (re.escape(self.endQuoteChar[:i]),
+                                               _escapeRegexRangeChars(self.endQuoteChar[i])) 
+                                    for i in range(len(self.endQuoteChar)-1,0,-1)]) + ')'
+                )
+        if escQuote:
+            self.pattern += (r'|(?:%s)' % re.escape(escQuote))
+        if escChar:
+            self.pattern += (r'|(?:%s.)' % re.escape(escChar))
+            self.escCharReplacePattern = re.escape(self.escChar)+"(.)"
+        self.pattern += (r')*%s' % re.escape(self.endQuoteChar))
+        
+        try:
+            self.re = re.compile(self.pattern, self.flags)
+            self.reString = self.pattern
+        except sre_constants.error,e:
+            warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern, 
+                SyntaxWarning, stacklevel=2)
+            raise
+
+        self.name = _ustr(self)
+        self.errmsg = "Expected " + self.name
+        self.myException.msg = self.errmsg
+        self.mayIndexError = False
+        self.mayReturnEmpty = True
+    
+    def parseImpl( self, instring, loc, doActions=True ):
+        result = instring[loc] == self.firstQuoteChar and self.re.match(instring,loc) or None
+        if not result:
+            exc = self.myException
+            exc.loc = loc
+            exc.pstr = instring
+            raise exc
+        
+        loc = result.end()
+        ret = result.group()
+        
+        if self.unquoteResults:
+            
+            # strip off quotes
+            ret = ret[self.quoteCharLen:-self.endQuoteCharLen]
+                
+            if isinstance(ret,basestring):
+                # replace escaped characters
+                if self.escChar:
+                    ret = re.sub(self.escCharReplacePattern,"\g<1>",ret)
+
+                # replace escaped quotes
+                if self.escQuote:
+                    ret = ret.replace(self.escQuote, self.endQuoteChar)
+
+        return loc, ret
+    
+    def __str__( self ):
+        try:
+            return super(QuotedString,self).__str__()
+        except:
+            pass
+        
+        if self.strRepr is None:
+            self.strRepr = "quoted string, starting with %s ending with %s" % (self.quoteChar, self.endQuoteChar)
+        
+        return self.strRepr
+
+
+class CharsNotIn(Token):
+    """Token for matching words composed of characters *not* in a given set.
+       Defined with string containing all disallowed characters, and an optional 
+       minimum, maximum, and/or exact length.
+    """
+    def __init__( self, notChars, min=1, max=0, exact=0 ):
+        super(CharsNotIn,self).__init__()
+        self.skipWhitespace = False
+        self.notChars = notChars
+        
+        self.minLen = min
+
+        if max > 0:
+            self.maxLen = max
+        else:
+            self.maxLen = sys.maxint
+
+        if exact > 0:
+            self.maxLen = exact
+            self.minLen = exact
+        
+        self.name = _ustr(self)
+        self.errmsg = "Expected " + self.name
+        self.mayReturnEmpty = ( self.minLen == 0 )
+        self.myException.msg = self.errmsg
+        self.mayIndexError = False
+
+    def parseImpl( self, instring, loc, doActions=True ):
+        if instring[loc] in self.notChars:
+            #~ raise ParseException( instring, loc, self.errmsg )
+            exc = self.myException
+            exc.loc = loc
+            exc.pstr = instring
+            raise exc
+            
+        start = loc
+        loc += 1
+        notchars = self.notChars
+        maxlen = min( start+self.maxLen, len(instring) )
+        while loc < maxlen and (instring[loc] not in notchars):
+            loc += 1
+
+        if loc - start < self.minLen:
+            #~ raise ParseException( instring, loc, self.errmsg )
+            exc = self.myException
+            exc.loc = loc
+            exc.pstr = instring
+            raise exc
+
+        return loc, instring[start:loc]
+
+    def __str__( self ):
+        try:
+            return super(CharsNotIn, self).__str__()
+        except:
+            pass
+
+        if self.strRepr is None:
+            if len(self.notChars) > 4:
+                self.strRepr = "!W:(%s...)" % self.notChars[:4]
+            else:
+                self.strRepr = "!W:(%s)" % self.notChars
+        
+        return self.strRepr
+
+class White(Token):
+    """Special matching class for matching whitespace.  Normally, whitespace is ignored
+       by pyparsing grammars.  This class is included when some whitespace structures
+       are significant.  Define with a string containing the whitespace characters to be
+       matched; default is " \\t\\n".  Also takes optional min, max, and exact arguments,
+       as defined for the Word class."""
+    whiteStrs = {
+        " " : "<SPC>",
+        "\t": "<TAB>",
+        "\n": "<LF>",
+        "\r": "<CR>",
+        "\f": "<FF>",
+        }
+    def __init__(self, ws=" \t\r\n", min=1, max=0, exact=0):
+        super(White,self).__init__()
+        self.matchWhite = ws
+        self.setWhitespaceChars( "".join([c for c in self.whiteChars if c not in self.matchWhite]) )
+        #~ self.leaveWhitespace()
+        self.name = ("".join([White.whiteStrs[c] for c in self.matchWhite]))
+        self.mayReturnEmpty = True
+        self.errmsg = "Expected " + self.name
+        self.myException.msg = self.errmsg
+
+        self.minLen = min
+
+        if max > 0:
+            self.maxLen = max
+        else:
+            self.maxLen = sys.maxint
+
+        if exact > 0:
+            self.maxLen = exact
+            self.minLen = exact
+            
+    def parseImpl( self, instring, loc, doActions=True ):
+        if not(instring[ loc ] in self.matchWhite):
+            #~ raise ParseException( instring, loc, self.errmsg )
+            exc = self.myException
+            exc.loc = loc
+            exc.pstr = instring
+            raise exc
+        start = loc
+        loc += 1
+        maxloc = start + self.maxLen
+        maxloc = min( maxloc, len(instring) )
+        while loc < maxloc and instring[loc] in self.matchWhite:
+            loc += 1
+
+        if loc - start < self.minLen:
+            #~ raise ParseException( instring, loc, self.errmsg )
+            exc = self.myException
+            exc.loc = loc
+            exc.pstr = instring
+            raise exc
+
+        return loc, instring[start:loc]
+
+
+class PositionToken(Token):
+    def __init__( self ):
+        super(PositionToken,self).__init__()
+        self.name=self.__class__.__name__
+        self.mayReturnEmpty = True
+        self.mayIndexError = False
+
+class GoToColumn(PositionToken):
+    """Token to advance to a specific column of input text; useful for tabular report scraping."""
+    def __init__( self, colno ):
+        super(GoToColumn,self).__init__()
+        self.col = colno
+
+    def preParse( self, instring, loc ):
+        if col(loc,instring) != self.col:
+            instrlen = len(instring)
+            if self.ignoreExprs:
+                loc = self.skipIgnorables( instring, loc )
+            while loc < instrlen and instring[loc].isspace() and col( loc, instring ) != self.col :
+                loc += 1
+        return loc
+
+    def parseImpl( self, instring, loc, doActions=True ):
+        thiscol = col( loc, instring )
+        if thiscol > self.col:
+            raise ParseException( instring, loc, "Text not in expected column", self )
+        newloc = loc + self.col - thiscol
+        ret = instring[ loc: newloc ]
+        return newloc, ret
+
+class LineStart(PositionToken):
+    """Matches if current position is at the beginning of a line within the parse string"""
+    def __init__( self ):
+        super(LineStart,self).__init__()
+        self.setWhitespaceChars( " \t" )
+        self.errmsg = "Expected start of line"
+        self.myException.msg = self.errmsg
+
+    def preParse( self, instring, loc ):
+        preloc = super(LineStart,self).preParse(instring,loc)
+        if instring[preloc] == "\n":
+            loc += 1
+        return loc
+
+    def parseImpl( self, instring, loc, doActions=True ):
+        if not( loc==0 or
+            (loc == self.preParse( instring, 0 )) or
+            (instring[loc-1] == "\n") ): #col(loc, instring) != 1:
+            #~ raise ParseException( instring, loc, "Expected start of line" )
+            exc = self.myException
+            exc.loc = loc
+            exc.pstr = instring
+            raise exc
+        return loc, []
+
+class LineEnd(PositionToken):
+    """Matches if current position is at the end of a line within the parse string"""
+    def __init__( self ):
+        super(LineEnd,self).__init__()
+        self.setWhitespaceChars( " \t" )
+        self.errmsg = "Expected end of line"
+        self.myException.msg = self.errmsg
+    
+    def parseImpl( self, instring, loc, doActions=True ):
+        if loc<len(instring):
+            if instring[loc] == "\n":
+                return loc+1, "\n"
+            else:
+                #~ raise ParseException( instring, loc, "Expected end of line" )
+                exc = self.myException
+                exc.loc = loc
+                exc.pstr = instring
+                raise exc
+        elif loc == len(instring):
+            return loc+1, []
+        else:
+            exc = self.myException
+            exc.loc = loc
+            exc.pstr = instring
+            raise exc
+
+class StringStart(PositionToken):
+    """Matches if current position is at the beginning of the parse string"""
+    def __init__( self ):
+        super(StringStart,self).__init__()
+        self.errmsg = "Expected start of text"
+        self.myException.msg = self.errmsg
+    
+    def parseImpl( self, instring, loc, doActions=True ):
+        if loc != 0:
+            # see if entire string up to here is just whitespace and ignoreables
+            if loc != self.preParse( instring, 0 ):
+                #~ raise ParseException( instring, loc, "Expected start of text" )
+                exc = self.myException
+                exc.loc = loc
+                exc.pstr = instring
+                raise exc
+        return loc, []
+
+class StringEnd(PositionToken):
+    """Matches if current position is at the end of the parse string"""
+    def __init__( self ):
+        super(StringEnd,self).__init__()
+        self.errmsg = "Expected end of text"
+        self.myException.msg = self.errmsg
+    
+    def parseImpl( self, instring, loc, doActions=True ):
+        if loc < len(instring):
+            #~ raise ParseException( instring, loc, "Expected end of text" )
+            exc = self.myException
+            exc.loc = loc
+            exc.pstr = instring
+            raise exc
+        elif loc == len(instring):
+            return loc+1, []
+        else:
+            exc = self.myException
+            exc.loc = loc
+            exc.pstr = instring
+            raise exc
+
+
+class ParseExpression(ParserElement):
+    """Abstract subclass of ParserElement, for combining and post-processing parsed tokens."""
+    def __init__( self, exprs, savelist = False ):
+        super(ParseExpression,self).__init__(savelist)
+        if isinstance( exprs, list ):
+            self.exprs = exprs
+        elif isinstance( exprs, basestring ):
+            self.exprs = [ Literal( exprs ) ]
+        else:
+            self.exprs = [ exprs ]
+
+    def __getitem__( self, i ):
+        return self.exprs[i]
+
+    def append( self, other ):
+        self.exprs.append( other )
+        self.strRepr = None
+        return self
+
+    def leaveWhitespace( self ):
+        """Extends leaveWhitespace defined in base class, and also invokes leaveWhitespace on
+           all contained expressions."""
+        self.skipWhitespace = False
+        self.exprs = [ e.copy() for e in self.exprs ]
+        for e in self.exprs:
+            e.leaveWhitespace()
+        return self
+
+    def ignore( self, other ):
+        if isinstance( other, Suppress ):
+            if other not in self.ignoreExprs:
+                super( ParseExpression, self).ignore( other )
+                for e in self.exprs:
+                    e.ignore( self.ignoreExprs[-1] )
+        else:
+            super( ParseExpression, self).ignore( other )
+            for e in self.exprs:
+                e.ignore( self.ignoreExprs[-1] )
+        return self
+
+    def __str__( self ):
+        try:
+            return super(ParseExpression,self).__str__()
+        except:
+            pass
+            
+        if self.strRepr is None:
+            self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.exprs) )
+        return self.strRepr
+
+    def streamline( self ):
+        super(ParseExpression,self).streamline()
+
+        for e in self.exprs:
+            e.streamline()
+
+        # collapse nested And's of the form And( And( And( a,b), c), d) to And( a,b,c,d )
+        # but only if there are no parse actions or resultsNames on the nested And's
+        # (likewise for Or's and MatchFirst's)
+        if ( len(self.exprs) == 2 ):
+            other = self.exprs[0]
+            if ( isinstance( other, self.__class__ ) and
+                  not(other.parseAction) and
+                  other.resultsName is None and
+                  not other.debug ):
+                self.exprs = other.exprs[:] + [ self.exprs[1] ]
+                self.strRepr = None
+                self.mayReturnEmpty |= other.mayReturnEmpty
+                self.mayIndexError  |= other.mayIndexError
+
+            other = self.exprs[-1]
+            if ( isinstance( other, self.__class__ ) and
+                  not(other.parseAction) and
+                  other.resultsName is None and
+                  not other.debug ):
+                self.exprs = self.exprs[:-1] + other.exprs[:]
+                self.strRepr = None
+                self.mayReturnEmpty |= other.mayReturnEmpty
+                self.mayIndexError  |= other.mayIndexError
+
+        return self
+
+    def setResultsName( self, name, listAllMatches=False ):
+        ret = super(ParseExpression,self).setResultsName(name,listAllMatches)
+        return ret
+    
+    def validate( self, validateTrace=[] ):
+        tmp = validateTrace[:]+[self]
+        for e in self.exprs:
+            e.validate(tmp)
+        self.checkRecursion( [] )
+
+class And(ParseExpression):
+    """Requires all given ParseExpressions to be found in the given order.
+       Expressions may be separated by whitespace.
+       May be constructed using the '+' operator.
+    """
+    def __init__( self, exprs, savelist = True ):
+        super(And,self).__init__(exprs, savelist)
+        self.mayReturnEmpty = True
+        for e in self.exprs:
+            if not e.mayReturnEmpty:
+                self.mayReturnEmpty = False
+                break
+        self.setWhitespaceChars( exprs[0].whiteChars )
+        self.skipWhitespace = exprs[0].skipWhitespace
+
+    def parseImpl( self, instring, loc, doActions=True ):
+        # pass False as last arg to _parse for first element, since we already
+        # pre-parsed the string as part of our And pre-parsing
+        loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False )
+        for e in self.exprs[1:]:
+            loc, exprtokens = e._parse( instring, loc, doActions )
+            if exprtokens or exprtokens.keys():
+                resultlist += exprtokens
+        return loc, resultlist
+
+    def __iadd__(self, other ):
+        if isinstance( other, basestring ):
+            other = Literal( other )
+        return self.append( other ) #And( [ self, other ] )
+        
+    def checkRecursion( self, parseElementList ):
+        subRecCheckList = parseElementList[:] + [ self ]
+        for e in self.exprs:
+            e.checkRecursion( subRecCheckList )
+            if not e.mayReturnEmpty:
+                break
+                
+    def __str__( self ):
+        if hasattr(self,"name"):
+            return self.name
+            
+        if self.strRepr is None:
+            self.strRepr = "{" + " ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
+        
+        return self.strRepr
+    
+
+class Or(ParseExpression):
+    """Requires that at least one ParseExpression is found.
+       If two expressions match, the expression that matches the longest string will be used.
+       May be constructed using the '^' operator.
+    """
+    def __init__( self, exprs, savelist = False ):
+        super(Or,self).__init__(exprs, savelist)
+        self.mayReturnEmpty = False
+        for e in self.exprs:
+            if e.mayReturnEmpty:
+                self.mayReturnEmpty = True
+                break
+    
+    def parseImpl( self, instring, loc, doActions=True ):
+        maxExcLoc = -1
+        maxMatchLoc = -1
+        for e in self.exprs:
+            try:
+                loc2 = e.tryParse( instring, loc )
+            except ParseException, err:
+                if err.loc > maxExcLoc:
+                    maxException = err
+                    maxExcLoc = err.loc
+            except IndexError, err:
+                if len(instring) > maxExcLoc:
+                    maxException = ParseException(instring,len(instring),e.errmsg,self)
+                    maxExcLoc = len(instring)
+            else:
+                if loc2 > maxMatchLoc:
+                    maxMatchLoc = loc2
+                    maxMatchExp = e
+        
+        if maxMatchLoc < 0:
+            if self.exprs:
+                raise maxException
+            else:
+                raise ParseException(instring, loc, "no defined alternatives to match", self)
+
+        return maxMatchExp._parse( instring, loc, doActions )
+
+    def __ixor__(self, other ):
+        if isinstance( other, basestring ):
+            other = Literal( other )
+        return self.append( other ) #Or( [ self, other ] )
+
+    def __str__( self ):
+        if hasattr(self,"name"):
+            return self.name
+            
+        if self.strRepr is None:
+            self.strRepr = "{" + " ^ ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
+        
+        return self.strRepr
+    
+    def checkRecursion( self, parseElementList ):
+        subRecCheckList = parseElementList[:] + [ self ]
+        for e in self.exprs:
+            e.checkRecursion( subRecCheckList )
+
+
+class MatchFirst(ParseExpression):
+    """Requires that at least one ParseExpression is found.
+       If two expressions match, the first one listed is the one that will match.
+       May be constructed using the '|' operator.
+    """
+    def __init__( self, exprs, savelist = False ):
+        super(MatchFirst,self).__init__(exprs, savelist)
+        if exprs:
+            self.mayReturnEmpty = False
+            for e in self.exprs:
+                if e.mayReturnEmpty:
+                    self.mayReturnEmpty = True
+                    break
+        else:
+            self.mayReturnEmpty = True
+    
+    def parseImpl( self, instring, loc, doActions=True ):
+        maxExcLoc = -1
+        for e in self.exprs:
+            try:
+                ret = e._parse( instring, loc, doActions )
+                return ret
+            except ParseException, err:
+                if err.loc > maxExcLoc:
+                    maxException = err
+                    maxExcLoc = err.loc
+            except IndexError, err:
+                if len(instring) > maxExcLoc:
+                    maxException = ParseException(instring,len(instring),e.errmsg,self)
+                    maxExcLoc = len(instring)
+
+        # only got here if no expression matched, raise exception for match that made it the furthest
+        else:
+            if self.exprs:
+                raise maxException
+            else:
+                raise ParseException(instring, loc, "no defined alternatives to match", self)
+
+    def __ior__(self, other ):
+        if isinstance( other, basestring ):
+            other = Literal( other )
+        return self.append( other ) #MatchFirst( [ self, other ] )
+
+    def __str__( self ):
+        if hasattr(self,"name"):
+            return self.name
+            
+        if self.strRepr is None:
+            self.strRepr = "{" + " | ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
+        
+        return self.strRepr
+    
+    def checkRecursion( self, parseElementList ):
+        subRecCheckList = parseElementList[:] + [ self ]
+        for e in self.exprs:
+            e.checkRecursion( subRecCheckList )
+
+class Each(ParseExpression):
+    """Requires all given ParseExpressions to be found, but in any order.
+       Expressions may be separated by whitespace.
+       May be constructed using the '&' operator.
+    """
+    def __init__( self, exprs, savelist = True ):
+        super(Each,self).__init__(exprs, savelist)
+        self.mayReturnEmpty = True
+        for e in self.exprs:
+            if not e.mayReturnEmpty:
+                self.mayReturnEmpty = False
+                break
+        self.skipWhitespace = True
+        self.optionals = [ e.expr for e in exprs if isinstance(e,Optional) ]
+        self.multioptionals = [ e.expr for e in exprs if isinstance(e,ZeroOrMore) ]
+        self.multirequired = [ e.expr for e in exprs if isinstance(e,OneOrMore) ]
+        self.required = [ e for e in exprs if not isinstance(e,(Optional,ZeroOrMore,OneOrMore)) ]
+        self.required += self.multirequired
+
+    def parseImpl( self, instring, loc, doActions=True ):
+        tmpLoc = loc
+        tmpReqd = self.required[:]
+        tmpOpt  = self.optionals[:]
+        matchOrder = []
+
+        keepMatching = True
+        while keepMatching:
+            tmpExprs = tmpReqd + tmpOpt + self.multioptionals + self.multirequired
+            failed = []
+            for e in tmpExprs:
+                try:
+                    tmpLoc = e.tryParse( instring, tmpLoc )
+                except ParseException:
+                    failed.append(e)
+                else:
+                    matchOrder.append(e)
+                    if e in tmpReqd:
+                        tmpReqd.remove(e)
+                    elif e in tmpOpt:
+                        tmpOpt.remove(e)
+            if len(failed) == len(tmpExprs):
+                keepMatching = False
+        
+        if tmpReqd:
+            missing = ", ".join( [ _ustr(e) for e in tmpReqd ] )
+            raise ParseException(instring,loc,"Missing one or more required elements (%s)" % missing )
+
+        resultlist = []
+        for e in matchOrder:
+            loc,results = e._parse(instring,loc,doActions)
+            resultlist.append(results)
+            
+        finalResults = ParseResults([])
+        for r in resultlist:
+            dups = {}
+            for k in r.keys():
+                if k in finalResults.keys():
+                    tmp = ParseResults(finalResults[k])
+                    tmp += ParseResults(r[k])
+                    dups[k] = tmp
+            finalResults += ParseResults(r)
+            for k,v in dups.items():
+                finalResults[k] = v
+        return loc, finalResults
+
+    def __str__( self ):
+        if hasattr(self,"name"):
+            return self.name
+            
+        if self.strRepr is None:
+            self.strRepr = "{" + " & ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
+        
+        return self.strRepr
+    
+    def checkRecursion( self, parseElementList ):
+        subRecCheckList = parseElementList[:] + [ self ]
+        for e in self.exprs:
+            e.checkRecursion( subRecCheckList )
+
+
+class ParseElementEnhance(ParserElement):
+    """Abstract subclass of ParserElement, for combining and post-processing parsed tokens."""
+    def __init__( self, expr, savelist=False ):
+        super(ParseElementEnhance,self).__init__(savelist)
+        if isinstance( expr, basestring ):
+            expr = Literal(expr)
+        self.expr = expr
+        self.strRepr = None
+        if expr is not None:
+            self.mayIndexError = expr.mayIndexError
+            self.setWhitespaceChars( expr.whiteChars )
+            self.skipWhitespace = expr.skipWhitespace
+            self.saveAsList = expr.saveAsList
+    
+    def parseImpl( self, instring, loc, doActions=True ):
+        if self.expr is not None:
+            return self.expr._parse( instring, loc, doActions, callPreParse=False )
+        else:
+            raise ParseException("",loc,self.errmsg,self)
+            
+    def leaveWhitespace( self ):
+        self.skipWhitespace = False
+        self.expr = self.expr.copy()
+        if self.expr is not None:
+            self.expr.leaveWhitespace()
+        return self
+
+    def ignore( self, other ):
+        if isinstance( other, Suppress ):
+            if other not in self.ignoreExprs:
+                super( ParseElementEnhance, self).ignore( other )
+                if self.expr is not None:
+                    self.expr.ignore( self.ignoreExprs[-1] )
+        else:
+            super( ParseElementEnhance, self).ignore( other )
+            if self.expr is not None:
+                self.expr.ignore( self.ignoreExprs[-1] )
+        return self
+
+    def streamline( self ):
+        super(ParseElementEnhance,self).streamline()
+        if self.expr is not None:
+            self.expr.streamline()
+        return self
+
+    def checkRecursion( self, parseElementList ):
+        if self in parseElementList:
+            raise RecursiveGrammarException( parseElementList+[self] )
+        subRecCheckList = parseElementList[:] + [ self ]
+        if self.expr is not None:
+            self.expr.checkRecursion( subRecCheckList )
+        
+    def validate( self, validateTrace=[] ):
+        tmp = validateTrace[:]+[self]
+        if self.expr is not None:
+            self.expr.validate(tmp)
+        self.checkRecursion( [] )
+    
+    def __str__( self ):
+        try:
+            return super(ParseElementEnhance,self).__str__()
+        except:
+            pass
+            
+        if self.strRepr is None and self.expr is not None:
+            self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.expr) )
+        return self.strRepr
+
+
+class FollowedBy(ParseElementEnhance):
+    """Lookahead matching of the given parse expression.  FollowedBy
+    does *not* advance the parsing position within the input string, it only 
+    verifies that the specified parse expression matches at the current 
+    position.  FollowedBy always returns a null token list."""
+    def __init__( self, expr ):
+        super(FollowedBy,self).__init__(expr)
+        self.mayReturnEmpty = True
+        
+    def parseImpl( self, instring, loc, doActions=True ):
+        self.expr.tryParse( instring, loc )
+        return loc, []
+
+
+class NotAny(ParseElementEnhance):
+    """Lookahead to disallow matching with the given parse expression.  NotAny
+    does *not* advance the parsing position within the input string, it only 
+    verifies that the specified parse expression does *not* match at the current 
+    position.  Also, NotAny does *not* skip over leading whitespace. NotAny 
+    always returns a null token list.  May be constructed using the '~' operator."""
+    def __init__( self, expr ):
+        super(NotAny,self).__init__(expr)
+        #~ self.leaveWhitespace()
+        self.skipWhitespace = False  # do NOT use self.leaveWhitespace(), don't want to propagate to exprs
+        self.mayReturnEmpty = True
+        self.errmsg = "Found unwanted token, "+_ustr(self.expr)
+        self.myException = ParseException("",0,self.errmsg,self)
+        
+    def parseImpl( self, instring, loc, doActions=True ):
+        try:
+            self.expr.tryParse( instring, loc )
+        except (ParseException,IndexError):
+            pass
+        else:
+            #~ raise ParseException(instring, loc, self.errmsg )
+            exc = self.myException
+            exc.loc = loc
+            exc.pstr = instring
+            raise exc
+        return loc, []
+
+    def __str__( self ):
+        if hasattr(self,"name"):
+            return self.name
+            
+        if self.strRepr is None:
+            self.strRepr = "~{" + _ustr(self.expr) + "}"
+        
+        return self.strRepr
+
+
+class ZeroOrMore(ParseElementEnhance):
+    """Optional repetition of zero or more of the given expression."""
+    def __init__( self, expr ):
+        super(ZeroOrMore,self).__init__(expr)
+        self.mayReturnEmpty = True
+    
+    def parseImpl( self, instring, loc, doActions=True ):
+        tokens = []
+        try:
+            loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
+            hasIgnoreExprs = ( len(self.ignoreExprs) > 0 )
+            while 1:
+                if hasIgnoreExprs:
+                    preloc = self.skipIgnorables( instring, loc )
+                else:
+                    preloc = loc
+                loc, tmptokens = self.expr._parse( instring, preloc, doActions )
+                if tmptokens or tmptokens.keys():
+                    tokens += tmptokens
+        except (ParseException,IndexError):
+            pass
+
+        return loc, tokens
+
+    def __str__( self ):
+        if hasattr(self,"name"):
+            return self.name
+            
+        if self.strRepr is None:
+            self.strRepr = "[" + _ustr(self.expr) + "]..."
+        
+        return self.strRepr
+    
+    def setResultsName( self, name, listAllMatches=False ):
+        ret = super(ZeroOrMore,self).setResultsName(name,listAllMatches)
+        ret.saveAsList = True
+        return ret
+    
+
+class OneOrMore(ParseElementEnhance):
+    """Repetition of one or more of the given expression."""
+    def parseImpl( self, instring, loc, doActions=True ):
+        # must be at least one
+        loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
+        try:
+            hasIgnoreExprs = ( len(self.ignoreExprs) > 0 )
+            while 1:
+                if hasIgnoreExprs:
+                    preloc = self.skipIgnorables( instring, loc )
+                else:
+                    preloc = loc
+                loc, tmptokens = self.expr._parse( instring, preloc, doActions )
+                if tmptokens or tmptokens.keys():
+                    tokens += tmptokens
+        except (ParseException,IndexError):
+            pass
+
+        return loc, tokens
+
+    def __str__( self ):
+        if hasattr(self,"name"):
+            return self.name
+            
+        if self.strRepr is None:
+            self.strRepr = "{" + _ustr(self.expr) + "}..."
+        
+        return self.strRepr
+    
+    def setResultsName( self, name, listAllMatches=False ):
+        ret = super(OneOrMore,self).setResultsName(name,listAllMatches)
+        ret.saveAsList = True
+        return ret
+
+class _NullToken(object):
+    def __bool__(self):
+        return False
+    def __str__(self):
+        return ""
+
+_optionalNotMatched = _NullToken()
+class Optional(ParseElementEnhance):
+    """Optional matching of the given expression.
+       A default return string can also be specified, if the optional expression
+       is not found.
+    """
+    def __init__( self, exprs, default=_optionalNotMatched ):
+        super(Optional,self).__init__( exprs, savelist=False )
+        self.defaultValue = default
+        self.mayReturnEmpty = True
+
+    def parseImpl( self, instring, loc, doActions=True ):
+        try:
+            loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
+        except (ParseException,IndexError):
+            if self.defaultValue is not _optionalNotMatched:
+                tokens = [ self.defaultValue ]
+            else:
+                tokens = []
+        return loc, tokens
+
+    def __str__( self ):
+        if hasattr(self,"name"):
+            return self.name
+            
+        if self.strRepr is None:
+            self.strRepr = "[" + _ustr(self.expr) + "]"
+        
+        return self.strRepr
+
+
+class SkipTo(ParseElementEnhance):
+    """Token for skipping over all undefined text until the matched expression is found.
+       If include is set to true, the matched expression is also consumed.  The ignore
+       argument is used to define grammars (typically quoted strings and comments) that 
+       might contain false matches.
+    """
+    def __init__( self, other, include=False, ignore=None ):
+        super( SkipTo, self ).__init__( other )
+        if ignore is not None:
+            self.expr = self.expr.copy()
+            self.expr.ignore(ignore)
+        self.mayReturnEmpty = True
+        self.mayIndexError = False
+        self.includeMatch = include
+        self.asList = False
+        self.errmsg = "No match found for "+_ustr(self.expr)
+        self.myException = ParseException("",0,self.errmsg,self)
+
+    def parseImpl( self, instring, loc, doActions=True ):
+        startLoc = loc
+        instrlen = len(instring)
+        expr = self.expr
+        while loc <= instrlen:
+            try:
+                loc = expr.skipIgnorables( instring, loc )
+                expr._parse( instring, loc, doActions=False, callPreParse=False )
+                if self.includeMatch:
+                    skipText = instring[startLoc:loc]
+                    loc,mat = expr._parse(instring,loc)
+                    if mat:
+                        return loc, [ skipText, mat ]
+                    else:
+                        return loc, [ skipText ]
+                else:
+                    return loc, [ instring[startLoc:loc] ]
+            except (ParseException,IndexError):
+                loc += 1
+        exc = self.myException
+        exc.loc = loc
+        exc.pstr = instring
+        raise exc
+
+class Forward(ParseElementEnhance):
+    """Forward declaration of an expression to be defined later -
+       used for recursive grammars, such as algebraic infix notation.
+       When the expression is known, it is assigned to the Forward variable using the '<<' operator.
+       
+       Note: take care when assigning to Forward not to overlook precedence of operators.
+       Specifically, '|' has a lower precedence than '<<', so that::
+          fwdExpr << a | b | c
+       will actually be evaluated as::
+          (fwdExpr << a) | b | c
+       thereby leaving b and c out as parseable alternatives.  It is recommended that you
+       explicitly group the values inserted into the Forward::
+          fwdExpr << (a | b | c)
+    """
+    def __init__( self, other=None ):
+        super(Forward,self).__init__( other, savelist=False )
+
+    def __lshift__( self, other ):
+        if isinstance( other, basestring ):
+            other = Literal(other)
+        self.expr = other
+        self.mayReturnEmpty = other.mayReturnEmpty
+        self.strRepr = None
+        return self
+
+    def leaveWhitespace( self ):
+        self.skipWhitespace = False
+        return self
+
+    def streamline( self ):
+        if not self.streamlined:
+            self.streamlined = True
+            if self.expr is not None: 
+                self.expr.streamline()
+        return self
+
+    def validate( self, validateTrace=[] ):
+        if self not in validateTrace:
+            tmp = validateTrace[:]+[self]
+            if self.expr is not None: 
+                self.expr.validate(tmp)
+        self.checkRecursion([])        
+        
+    def __str__( self ):
+        if hasattr(self,"name"):
+            return self.name
+
+        self.__class__ = _ForwardNoRecurse
+        try:
+            if self.expr is not None: 
+                retString = _ustr(self.expr)
+            else:
+                retString = "None"
+        finally:
+            self.__class__ = Forward
+        return "Forward: "+retString
+        
+    def copy(self):
+        if self.expr is not None:
+            return super(Forward,self).copy()
+        else:
+            ret = Forward()
+            ret << self
+            return ret
+
+class _ForwardNoRecurse(Forward):
+    def __str__( self ):
+        return "..."
+        
+class TokenConverter(ParseElementEnhance):
+    """Abstract subclass of ParseExpression, for converting parsed results."""
+    def __init__( self, expr, savelist=False ):
+        super(TokenConverter,self).__init__( expr )#, savelist )
+        self.saveAsList = False
+
+
+class Upcase(TokenConverter):
+    """Converter to upper case all matching tokens."""
+    def __init__(self, *args):
+        super(Upcase,self).__init__(*args)
+        warnings.warn("Upcase class is deprecated, use upcaseTokens parse action instead", 
+                       DeprecationWarning,stacklevel=2)
+    
+    def postParse( self, instring, loc, tokenlist ):
+        return map( string.upper, tokenlist )
+
+
+class Combine(TokenConverter):
+    """Converter to concatenate all matching tokens to a single string.
+       By default, the matching patterns must also be contiguous in the input string;
+       this can be disabled by specifying 'adjacent=False' in the constructor.
+    """
+    def __init__( self, expr, joinString="", adjacent=True ):
+        super(Combine,self).__init__( expr )
+        # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself
+        if adjacent:
+            self.leaveWhitespace()
+        self.adjacent = adjacent
+        self.skipWhitespace = True
+        self.joinString = joinString
+
+    def ignore( self, other ):
+        if self.adjacent:
+            ParserElement.ignore(self, other)
+        else:
+            super( Combine, self).ignore( other )
+        return self
+
+    def postParse( self, instring, loc, tokenlist ):
+        retToks = tokenlist.copy()
+        del retToks[:]
+        retToks += ParseResults([ "".join(tokenlist._asStringList(self.joinString)) ], modal=self.modalResults)
+
+        if self.resultsName and len(retToks.keys())>0:
+            return [ retToks ]
+        else:
+            return retToks
+
+class Group(TokenConverter):
+    """Converter to return the matched tokens as a list - useful for returning tokens of ZeroOrMore and OneOrMore expressions."""
+    def __init__( self, expr ):
+        super(Group,self).__init__( expr )
+        self.saveAsList = True
+
+    def postParse( self, instring, loc, tokenlist ):
+        return [ tokenlist ]
+        
+class Dict(TokenConverter):
+    """Converter to return a repetitive expression as a list, but also as a dictionary.
+       Each element can also be referenced using the first token in the expression as its key.
+       Useful for tabular report scraping when the first column can be used as a item key.
+    """
+    def __init__( self, exprs ):
+        super(Dict,self).__init__( exprs )
+        self.saveAsList = True
+
+    def postParse( self, instring, loc, tokenlist ):
+        for i,tok in enumerate(tokenlist):
+            ikey = _ustr(tok[0]).strip()
+            if len(tok)==1:
+                tokenlist[ikey] = ("",i)
+            elif len(tok)==2 and not isinstance(tok[1],ParseResults):
+                tokenlist[ikey] = (tok[1],i)
+            else:
+                dictvalue = tok.copy() #ParseResults(i)
+                del dictvalue[0]
+                if len(dictvalue)!= 1 or (isinstance(dictvalue,ParseResults) and dictvalue.keys()):
+                    tokenlist[ikey] = (dictvalue,i)
+                else:
+                    tokenlist[ikey] = (dictvalue[0],i)
+
+        if self.resultsName:
+            return [ tokenlist ]
+        else:
+            return tokenlist
+
+
+class Suppress(TokenConverter):
+    """Converter for ignoring the results of a parsed expression."""
+    def postParse( self, instring, loc, tokenlist ):
+        return []
+    
+    def suppress( self ):
+        return self
+
+
+class OnlyOnce(object):
+    """Wrapper for parse actions, to ensure they are only called once."""
+    def __init__(self, methodCall):
+        self.callable = ParserElement.normalizeParseActionArgs(methodCall)
+        self.called = False
+    def __call__(self,s,l,t):
+        if not self.called:
+            results = self.callable(s,l,t)
+            self.called = True
+            return results
+        raise ParseException(s,l,"")
+    def reset():
+        self.called = False
+
+def traceParseAction(f):
+    """Decorator for debugging parse actions."""
+    f = ParserElement.normalizeParseActionArgs(f)
+    def z(*paArgs):
+        thisFunc = f.func_name
+        s,l,t = paArgs[-3:]
+        if len(paArgs)>3:
+            thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc
+        sys.stderr.write( ">>entering %s(line: '%s', %d, %s)\n" % (thisFunc,line(l,s),l,t) )
+        try:
+            ret = f(*paArgs)
+        except Exception, exc:
+            sys.stderr.write( "<<leaving %s (exception: %s)\n" % (thisFunc,exc) )
+            raise
+        sys.stderr.write( "<<leaving %s (ret: %s)\n" % (thisFunc,ret) )
+        return ret
+    return z
+        
+#
+# global helpers
+#
+def delimitedList( expr, delim=",", combine=False ):
+    """Helper to define a delimited list of expressions - the delimiter defaults to ','.
+       By default, the list elements and delimiters can have intervening whitespace, and 
+       comments, but this can be overridden by passing 'combine=True' in the constructor.
+       If combine is set to True, the matching tokens are returned as a single token
+       string, with the delimiters included; otherwise, the matching tokens are returned
+       as a list of tokens, with the delimiters suppressed.
+    """
+    dlName = _ustr(expr)+" ["+_ustr(delim)+" "+_ustr(expr)+"]..."
+    if combine:
+        return Combine( expr + ZeroOrMore( delim + expr ) ).setName(dlName)
+    else:
+        return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName)
+
+def countedArray( expr ):
+    """Helper to define a counted list of expressions.
+       This helper defines a pattern of the form::
+           integer expr expr expr...
+       where the leading integer tells how many expr expressions follow.
+       The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed.
+    """
+    arrayExpr = Forward()
+    def countFieldParseAction(s,l,t):
+        n = int(t[0])
+        arrayExpr << (n and Group(And([expr]*n)) or Group(empty))
+        return []
+    return ( Word(nums).setParseAction(countFieldParseAction) + arrayExpr )
+
+def _flatten(L):
+    if type(L) is not list: return [L]
+    if L == []: return L
+    return _flatten(L[0]) + _flatten(L[1:])
+
+def matchPreviousLiteral(expr):
+    """Helper to define an expression that is indirectly defined from
+       the tokens matched in a previous expression, that is, it looks
+       for a 'repeat' of a previous expression.  For example::
+           first = Word(nums)
+           second = matchPreviousLiteral(first)
+           matchExpr = first + ":" + second
+       will match "1:1", but not "1:2".  Because this matches a 
+       previous literal, will also match the leading "1:1" in "1:10".  
+       If this is not desired, use matchPreviousExpr.
+       Do *not* use with packrat parsing enabled.
+    """
+    rep = Forward()
+    def copyTokenToRepeater(s,l,t):
+        if t:
+            if len(t) == 1:
+                rep << t[0]
+            else:
+                # flatten t tokens
+                tflat = _flatten(t.asList())
+                rep << And( [ Literal(tt) for tt in tflat ] )
+        else:
+            rep << Empty()
+    expr.addParseAction(copyTokenToRepeater)
+    return rep
+    
+def matchPreviousExpr(expr):
+    """Helper to define an expression that is indirectly defined from
+       the tokens matched in a previous expression, that is, it looks
+       for a 'repeat' of a previous expression.  For example::
+           first = Word(nums)
+           second = matchPreviousExpr(first)
+           matchExpr = first + ":" + second
+       will match "1:1", but not "1:2".  Because this matches by
+       expressions, will *not* match the leading "1:1" in "1:10";
+       the expressions are evaluated first, and then compared, so
+       "1" is compared with "10".
+       Do *not* use with packrat parsing enabled.
+    """
+    rep = Forward()
+    e2 = expr.copy()
+    rep << e2
+    def copyTokenToRepeater(s,l,t):
+        matchTokens = _flatten(t.asList())
+        def mustMatchTheseTokens(s,l,t):
+            theseTokens = _flatten(t.asList())
+            if  theseTokens != matchTokens:
+                raise ParseException("",0,"")
+        rep.setParseAction( mustMatchTheseTokens )
+    expr.addParseAction(copyTokenToRepeater)
+    return rep
+    
+def _escapeRegexRangeChars(s):
+    #~  escape these chars: ^-]
+    for c in r"\^-]":
+        s = s.replace(c,"\\"+c)
+    s = s.replace("\n",r"\n")
+    s = s.replace("\t",r"\t")
+    return _ustr(s)
+    
+def oneOf( strs, caseless=False, useRegex=True ):
+    """Helper to quickly define a set of alternative Literals, and makes sure to do 
+       longest-first testing when there is a conflict, regardless of the input order, 
+       but returns a MatchFirst for best performance.  
+       
+       Parameters:
+        - strs - a string of space-delimited literals, or a list of string literals
+        - caseless - (default=False) - treat all literals as caseless
+        - useRegex - (default=True) - as an optimization, will generate a Regex
+          object; otherwise, will generate a MatchFirst object (if caseless=True, or
+          if creating a Regex raises an exception)
+    """
+    if caseless:
+        isequal = ( lambda a,b: a.upper() == b.upper() )
+        masks = ( lambda a,b: b.upper().startswith(a.upper()) )
+        parseElementClass = CaselessLiteral
+    else:
+        isequal = ( lambda a,b: a == b )
+        masks = ( lambda a,b: b.startswith(a) )
+        parseElementClass = Literal
+    
+    if isinstance(strs,(list,tuple)):
+        symbols = strs[:]
+    elif isinstance(strs,basestring):
+        symbols = strs.split()
+    else:
+        warnings.warn("Invalid argument to oneOf, expected string or list",
+                SyntaxWarning, stacklevel=2)
+        
+    i = 0
+    while i < len(symbols)-1:
+        cur = symbols[i]
+        for j,other in enumerate(symbols[i+1:]):
+            if ( isequal(other, cur) ):
+                del symbols[i+j+1]
+                break
+            elif ( masks(cur, other) ):
+                del symbols[i+j+1]
+                symbols.insert(i,other)
+                cur = other
+                break
+        else:
+            i += 1
+
+    if not caseless and useRegex:
+        #~ print strs,"->", "|".join( [ _escapeRegexChars(sym) for sym in symbols] )
+        try:
+            if len(symbols)==len("".join(symbols)):
+                return Regex( "[%s]" % "".join( [ _escapeRegexRangeChars(sym) for sym in symbols] ) )
+            else:
+                return Regex( "|".join( [ re.escape(sym) for sym in symbols] ) )
+        except:
+            warnings.warn("Exception creating Regex for oneOf, building MatchFirst",
+                    SyntaxWarning, stacklevel=2)
+
+
+    # last resort, just use MatchFirst
+    return MatchFirst( [ parseElementClass(sym) for sym in symbols ] )
+
+def dictOf( key, value ):
+    """Helper to easily and clearly define a dictionary by specifying the respective patterns
+       for the key and value.  Takes care of defining the Dict, ZeroOrMore, and Group tokens
+       in the proper order.  The key pattern can include delimiting markers or punctuation,
+       as long as they are suppressed, thereby leaving the significant key text.  The value
+       pattern can include named results, so that the Dict results can include named token 
+       fields.
+    """
+    return Dict( ZeroOrMore( Group ( key + value ) ) )
+
+_bslash = "\\"
+printables = "".join( [ c for c in string.printable if c not in string.whitespace ] )
+
+# convenience constants for positional expressions
+empty       = Empty().setName("empty")
+lineStart   = LineStart().setName("lineStart")
+lineEnd     = LineEnd().setName("lineEnd")
+stringStart = StringStart().setName("stringStart")
+stringEnd   = StringEnd().setName("stringEnd")
+
+_escapedPunc = Word( _bslash, r"\[]-*.$+^?()~ ", exact=2 ).setParseAction(lambda s,l,t:t[0][1])
+_printables_less_backslash = "".join([ c for c in printables if c not in  r"\]" ])
+_escapedHexChar = Combine( Suppress(_bslash + "0x") + Word(hexnums) ).setParseAction(lambda s,l,t:unichr(int(t[0],16)))
+_escapedOctChar = Combine( Suppress(_bslash) + Word("0","01234567") ).setParseAction(lambda s,l,t:unichr(int(t[0],8)))
+_singleChar = _escapedPunc | _escapedHexChar | _escapedOctChar | Word(_printables_less_backslash,exact=1)
+_charRange = Group(_singleChar + Suppress("-") + _singleChar)
+_reBracketExpr = "[" + Optional("^").setResultsName("negate") + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") + "]"
+
+_expanded = lambda p: (isinstance(p,ParseResults) and ''.join([ unichr(c) for c in range(ord(p[0]),ord(p[1])+1) ]) or p)
+        
+def srange(s):
+    r"""Helper to easily define string ranges for use in Word construction.  Borrows
+       syntax from regexp '[]' string range definitions::
+          srange("[0-9]")   -> "0123456789"
+          srange("[a-z]")   -> "abcdefghijklmnopqrstuvwxyz"
+          srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
+       The input string must be enclosed in []'s, and the returned string is the expanded 
+       character set joined into a single string.
+       The values enclosed in the []'s may be::
+          a single character
+          an escaped character with a leading backslash (such as \- or \])
+          an escaped hex character with a leading '\0x' (\0x21, which is a '!' character)
+          an escaped octal character with a leading '\0' (\041, which is a '!' character)
+          a range of any of the above, separated by a dash ('a-z', etc.)
+          any combination of the above ('aeiouy', 'a-zA-Z0-9_$', etc.)
+    """
+    try:
+        return "".join([_expanded(part) for part in _reBracketExpr.parseString(s).body])
+    except:
+        return ""
+
+def replaceWith(replStr):
+    """Helper method for common parse actions that simply return a literal value.  Especially 
+       useful when used with transformString().
+    """
+    def _replFunc(*args):
+        return [replStr]
+    return _replFunc
+
+def removeQuotes(s,l,t):
+    """Helper parse action for removing quotation marks from parsed quoted strings.
+       To use, add this parse action to quoted string using::
+         quotedString.setParseAction( removeQuotes )
+    """
+    return t[0][1:-1]
+
+def upcaseTokens(s,l,t):
+    """Helper parse action to convert tokens to upper case."""
+    return [ str(tt).upper() for tt in t ]
+
+def downcaseTokens(s,l,t):
+    """Helper parse action to convert tokens to lower case."""
+    return [ str(tt).lower() for tt in t ]
+
+def keepOriginalText(s,startLoc,t):
+    import inspect
+    """Helper parse action to preserve original parsed text,
+       overriding any nested parse actions."""
+    f = inspect.stack()[1][0]
+    try:
+        endloc = f.f_locals["loc"]
+    finally:
+        del f
+    return s[startLoc:endloc]
+        
+def _makeTags(tagStr, xml):
+    """Internal helper to construct opening and closing tag expressions, given a tag name"""
+    if isinstance(tagStr,basestring):
+        resname = tagStr
+        tagStr = Keyword(tagStr, caseless=not xml)
+    else:
+        resname = tagStr.name
+        
+    tagAttrName = Word(alphas,alphanums+"_-")
+    if (xml):
+        tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes )
+        openTag = Suppress("<") + tagStr + \
+                Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \
+                Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
+    else:
+        printablesLessRAbrack = "".join( [ c for c in printables if c not in ">" ] )
+        tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack)
+        openTag = Suppress("<") + tagStr + \
+                Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \
+                Suppress("=") + tagAttrValue ))) + \
+                Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
+    closeTag = Combine("</" + tagStr + ">")
+    
+    openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % tagStr)
+    closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("</%s>" % tagStr)
+    
+    return openTag, closeTag
+
+def makeHTMLTags(tagStr):
+    """Helper to construct opening and closing tag expressions for HTML, given a tag name"""
+    return _makeTags( tagStr, False )
+
+def makeXMLTags(tagStr):
+    """Helper to construct opening and closing tag expressions for XML, given a tag name"""
+    return _makeTags( tagStr, True )
+
+opAssoc = _Constants()
+opAssoc.LEFT = object()
+opAssoc.RIGHT = object()
+
+def operatorPrecedence( baseExpr, opList ):
+    """Helper method for constructing grammars of expressions made up of 
+       operators working in a precedence hierarchy.  Operators may be unary or
+       binary, left- or right-associative.  Parse actions can also be attached
+       to operator expressions.
+        
+       Parameters:
+        - baseExpr - expression representing the most basic element for the nested 
+        - opList - list of tuples, one for each operator precedence level in the expression grammar; each tuple is of the form
+          (opExpr, numTerms, rightLeftAssoc, parseAction), where:
+           - opExpr is the pyparsing expression for the operator;
+              may also be a string, which will be converted to a Literal
+           - numTerms is the number of terms for this operator (must
+              be 1 or 2)
+           - rightLeftAssoc is the indicator whether the operator is
+              right or left associative, using the pyparsing-defined
+              constants opAssoc.RIGHT and opAssoc.LEFT.
+           - parseAction is the parse action to be associated with 
+              expressions matching this operator expression (the
+              parse action tuple member may be omitted)
+    """
+    ret = Forward()
+    lastExpr = baseExpr | ( Suppress('(') + ret + Suppress(')') )
+    for i,operDef in enumerate(opList):
+        opExpr,arity,rightLeftAssoc,pa = (operDef + (None,))[:4]
+        thisExpr = Forward().setName("expr%d" % i)
+        if rightLeftAssoc == opAssoc.LEFT:
+            if arity == 1:
+                matchExpr = Group( lastExpr + opExpr )
+            elif arity == 2:
+                matchExpr = Group( lastExpr + OneOrMore( opExpr + lastExpr ) )
+            else:
+                raise ValueError, "operator must be unary (1) or binary (2)"
+        elif rightLeftAssoc == opAssoc.RIGHT:
+            if arity == 1:
+                # try to avoid LR with this extra test
+                if not isinstance(opExpr, Optional):
+                    opExpr = Optional(opExpr)
+                matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group( opExpr + thisExpr ) 
+            elif arity == 2:
+                matchExpr = Group( lastExpr + OneOrMore( opExpr + thisExpr ) )
+            else:
+                raise ValueError, "operator must be unary (1) or binary (2)"
+        else:
+            raise ValueError, "operator must indicate right or left associativity"
+        if pa:
+            matchExpr.setParseAction( pa )
+        thisExpr << ( matchExpr | lastExpr )
+        lastExpr = thisExpr
+    ret << lastExpr
+    return ret
+
+alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]")
+punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]")
+
+dblQuotedString = Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\.))*"').setName("string enclosed in double quotes")
+sglQuotedString = Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\.))*'").setName("string enclosed in single quotes")
+quotedString = Regex(r'''(?:"(?:[^"\n\r\\]|(?:"")|(?:\\.))*")|(?:'(?:[^'\n\r\\]|(?:'')|(?:\\.))*')''').setName("quotedString using single or double quotes")
+
+anyOpenTag,anyCloseTag = makeHTMLTags(Word(alphas,alphanums+"_"))
+commonHTMLEntity = Combine("&" + oneOf("gt lt amp nbsp quot").setResultsName("entity") +";")
+_htmlEntityMap = dict(zip("gt lt amp nbsp quot".split(),"><& '"))
+replaceHTMLEntity = lambda t : t.entity in _htmlEntityMap and _htmlEntityMap[t.entity] or None
+    
+# it's easy to get these comment structures wrong - they're very common, so may as well make them available
+cStyleComment = Regex(r"/\*(?:[^*]*\*+)+?/").setName("C style comment")
+
+htmlComment = Regex(r"<!--[\s\S]*?-->")
+restOfLine = Regex(r".*").leaveWhitespace()
+dblSlashComment = Regex(r"\/\/(\\\n|.)*").setName("// comment")
+cppStyleComment = Regex(r"/(?:\*(?:[^*]*\*+)+?/|/[^\n]*(?:\n[^\n]*)*?(?:(?<!\\)|\Z))").setName("C++ style comment")
+
+javaStyleComment = cppStyleComment
+pythonStyleComment = Regex(r"#.*").setName("Python style comment")
+_noncomma = "".join( [ c for c in printables if c != "," ] )
+_commasepitem = Combine(OneOrMore(Word(_noncomma) + 
+                                  Optional( Word(" \t") + 
+                                            ~Literal(",") + ~LineEnd() ) ) ).streamline().setName("commaItem")
+commaSeparatedList = delimitedList( Optional( quotedString | _commasepitem, default="") ).setName("commaSeparatedList")
+
+
+if __name__ == "__main__":
+
+    def test( teststring ):
+        print teststring,"->",
+        try:
+            tokens = simpleSQL.parseString( teststring )
+            tokenlist = tokens.asList()
+            print tokenlist
+            print "tokens = ",        tokens
+            print "tokens.columns =", tokens.columns
+            print "tokens.tables =",  tokens.tables
+            print tokens.asXML("SQL",True)
+        except ParseException, err:
+            print err.line
+            print " "*(err.column-1) + "^"
+            print err
+        print
+
+    selectToken    = CaselessLiteral( "select" )
+    fromToken      = CaselessLiteral( "from" )
+
+    ident          = Word( alphas, alphanums + "_$" )
+    columnName     = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens )
+    columnNameList = Group( delimitedList( columnName ) )#.setName("columns")
+    tableName      = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens )
+    tableNameList  = Group( delimitedList( tableName ) )#.setName("tables")
+    simpleSQL      = ( selectToken + \
+                     ( '*' | columnNameList ).setResultsName( "columns" ) + \
+                     fromToken + \
+                     tableNameList.setResultsName( "tables" ) )
+    
+    test( "SELECT * from XYZZY, ABC" )
+    test( "select * from SYS.XYZZY" )
+    test( "Select A from Sys.dual" )
+    test( "Select AA,BB,CC from Sys.dual" )
+    test( "Select A, B, C from Sys.dual" )
+    test( "Select A, B, C from Sys.dual" )
+    test( "Xelect A, B, C from Sys.dual" )
+    test( "Select A, B, C frox Sys.dual" )
+    test( "Select" )
+    test( "Select ^^^ frox Sys.dual" )
+    test( "Select A, B, C from Sys.dual, Table2   " )
--- a/sbsv2/raptor/python/raptor.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/raptor.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,1234 +1,1407 @@
-#
-# 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: 
-# raptor module
-# This module represents the running Raptor program. Raptor is started
-# either by calling the Main() function, which creates an instance of
-# the raptor.Raptor class and calls its methods to perform a build based
-# on command-line parameters, or by explicitly creating a raptor.Raptor
-# instance and calling its methods to set-up and perform a build.
-#
-
-name = "sbs"			# the public name for the raptor build tool
-env  = "SBS_HOME"		# the environment variable that locates us
-xml  = "sbs_init.xml"	# the primary initialisation file
-env2 = "HOME"		 	# the environment variable that locates the user
-xml2 = ".sbs_init.xml"	# the override initialisation file
-
-import generic_path
-import os
-import raptor_cache
-import raptor_cli
-import raptor_data
-import raptor_make
-import raptor_meta
-import raptor_utilities
-import raptor_version
-import raptor_xml
-import filter_list
-import sys
-import types
-import time
-import re
-import traceback
-import pluginbox
-from xml.sax.saxutils import escape
-
-
-if not "HOSTPLATFORM" in os.environ or not "HOSTPLATFORM_DIR" in os.environ:
-	print "Error: HOSTPLATFORM and HOSTPLATFORM_DIR must be set in the environment (this is usually done automatically by the startup script)."
-	sys.exit(1)
-
-hostplatform = os.environ["HOSTPLATFORM"].split(" ")
-hostplatform_dir = os.environ["HOSTPLATFORM_DIR"]
-
-# defaults can use EPOCROOT
-if "EPOCROOT" in os.environ:
-	epocroot = os.environ["EPOCROOT"].replace("\\","/")
-else:
-	if 'linux' in hostplatform:
-		epocroot=os.environ['HOME'] + os.sep + "epocroot"
-		os.environ["EPOCROOT"] = epocroot
-	else:
-		epocroot = "/"
-		os.environ["EPOCROOT"] = os.sep
-
-if "SBS_BUILD_DIR" in os.environ:
-	sbs_build_dir = os.environ["SBS_BUILD_DIR"]
-else:
-	sbs_build_dir = (epocroot + "/epoc32/build").replace("//","/")
-
-
-
-# only use default XML from the epoc32 tree if it exists
-defaultSystemConfig = "lib/config"
-epoc32UserConfigDir = generic_path.Join(epocroot, "epoc32/sbs_config")
-if epoc32UserConfigDir.isDir():
-	defaultSystemConfig = str(epoc32UserConfigDir) + os.pathsep + defaultSystemConfig
-
-# parameters that can be overriden by the sbs_init.xml file
-# or by the command-line.
-defaults = {
-		"allowCommandLineOverrides" : True,
-		"CLI" : "raptor_cli",
-		"buildInformation" : generic_path.Path("bld.inf"),
-		"defaultConfig" : "default",
-		"jobs": 4,
-		"keepGoing": False,
-		"logFileName" : generic_path.Join(sbs_build_dir,"Makefile.%TIME.log"),
-		"makeEngine" : "make",
-		"preferBuildInfoToSystemDefinition" : False,
-		"pruneDuplicateMakefiles": True,
-		"quiet" : False,
-		"systemConfig" :  defaultSystemConfig,
-		"systemDefinition" : generic_path.Path("System_Definition.xml"),
-		"systemDefinitionBase" : generic_path.Path("."),
-		"systemFLM" : generic_path.Path("lib/flm"),
-		"systemPlugins" : generic_path.Path("python/plugins"),
-		"topMakefile" : generic_path.Join(sbs_build_dir,"Makefile"),
-		"tries": 1,
-		"writeSingleMakefile": True,
-		"ignoreOsDetection": False,
-		"toolcheck": "on",
-		"filterList": "filterterminal,filterlogfile"
-		}
-
-
-class ComponentGroup(object):
-	""" 	Some components that should be built togther 
-		e.g. a Layer in the system definition. 
-	""" 
-	def __init__(self, name, componentlist=[]):
-		self.components = componentlist
-		self.name = name
-
-	def __iter__(self):
-		return iter(self.components)
-
-	def __getitem__(self,x):
-		if isinstance(x, slice):
-			return self.components[x.start:x.stop]
-		return self.components[x]
-
-	def __setitem__(self,k, v):
-		self.components[k] = v
-
-	def __len__(self):
-		return len(self.components)
-
-	def extend(self, c):
-		self.components.extend(c)
-	
-	def append(self, c):
-		self.components.append(c)
-
-	def GenerateSpecs(self, genericspecs, configs):
-		"""Return a build spec hierarchy for a ComponentGroup. This involves parsing the component MetaData (bld.infs, mmps). 
-		Takes a raptor object as a parameter (build), together with a list of Configurations.
-
-		Returns a tuple consisting of a list of specification objects and a list of dependency files
-		that relate to these specs.
-		"""
-
-		self.specs = []
-		self.specs.extend(genericspecs)
-		self.configs = configs
-		self.dependencies = set()
-
-		metaReader = None
-		if len (self.components):
-			try:
-				# create a MetaReader that is aware of the list of
-				# configurations that we are trying to build.
-				metaReader = raptor_meta.MetaReader(build, configs)
-
-				# convert the list of bld.inf files into a specification
-				# hierarchy suitable for all the configurations we are using.
-				self.specs.extend(metaReader.ReadBldInfFiles(self.components,build.doExportOnly))
-
-			except raptor_meta.MetaDataError, e:
-				log.Error(e.Text)
-
-		log.Info("Buildable specification group '%s'", name)
-		build.AttachSpecs(self.specs)
-
-		# Get a unique list of the dependency files that were created
-		if metaReader:
-			for c in metaReader.BuildPlatforms:
-				self.dependencies.update(c["METADEPS"])
-
-
-	def CreateMakefile(self, makefilename_base, engine, named = False):
-		if len(self.specs) <= 0:
-			return None
-
-		if named:
-			makefile = generic_path.Path(str(makefilename_base) + "_" + raptor_utilities.sanitise(self.name))
-		else:
-			makefile = generic_path.Path(str(makefilename_base))
-
-		# insert the start time into the Makefile name?
-		makefile.path = makefile.path.replace("%TIME", build.timestring)
-
-		engine.Write(makefile, self.specs, self.configs)
-
-		return makefile
-
-
-	def GenerateMetadataSpecs(self, configs):
-		# insert the start time into the Makefile name?
-
-		self.configs = build.GetConfig("build").GenerateBuildUnits()
-
-		# Pass certain CLI flags through to the makefile-generating sbs calls
-		cli_options = ""
-			
-		if build.debugOutput == True:
-			cli_options += " -d"
-				
-		if build.ignoreOsDetection == True:
-			cli_options += " -i"
-			
-		if build.keepGoing == True:
-			cli_options += " -k"
-			
-		if build.quiet == True:
-			cli_options += " -q"
-
-		
-		nc = len(self.components)
-		number_blocks = 16
-		block_size = (nc / number_blocks) + 1
-		component_blocks = []
-		spec_nodes = []
-		
-		b = 0
-		while b < nc:
-			component_blocks.append(self.components[b:b+block_size])
-			b += block_size
-			
-		if len(component_blocks[-1]) <= 0:
-			component_blocks.pop()
-		
-		loop_number = 0
-		for block in component_blocks:
-			loop_number += 1
-			specNode = raptor_data.Specification("metadata_" + self.name)
-
-			componentList = " ".join([str(c) for c in block])
-			configList = " ".join([c.name for c in configs])
-			
-			makefile_path = str(build.topMakefile) + "_" + str(loop_number)
-			try:
-				os.unlink(makefile_path) # until we have dependencies working properly
-			except Exception,e:
-				# print "couldn't unlink %s: %s" %(componentMakefileName, str(e))
-				pass
-			
-			# add some basic data in a component-wide variant
-			var = raptor_data.Variant()
-			var.AddOperation(raptor_data.Set("COMPONENT_PATHS", componentList))
-			var.AddOperation(raptor_data.Set("MAKEFILE_PATH", makefile_path))
-			var.AddOperation(raptor_data.Set("CONFIGS", configList))
-			var.AddOperation(raptor_data.Set("CLI_OPTIONS", cli_options))
-			# Pass on '-n' (if specified) to the makefile-generating sbs calls
-			if build.noBuild:
-				var.AddOperation(raptor_data.Set("NO_BUILD", "1"))
-			specNode.AddVariant(var)
-	
-	
-	
-			try:
-				interface = build.cache.FindNamedInterface("build.makefiles")
-				specNode.SetInterface(interface)
-			except KeyError:
-				build.Error("Can't find flm interface 'build.makefiles' ")
-				
-			spec_nodes.append(specNode)
-			
-			
-
-		## possibly some error handling here?
-
-		self.specs = spec_nodes
-
-
-class BuildCompleteException(Exception):
-	pass
-
-# raptor module classes
-
-class Raptor(object):
-	"""An instance of a running Raptor program.
-
-	When operated from the command-line there is a single Raptor object
-	created by the Main function. When operated by an IDE several Raptor
-	objects may be created and operated at the same time."""
-
-
-	M_BUILD = 1
-	M_VERSION = 2	
-
-	def __init__(self, home = None):
-
-		self.DefaultSetUp(home)
-
-
-	def DefaultSetUp(self, home = None):
-		"revert to the default set-up state"
-		self.errorCode = 0
-		self.skipAll = False
-		self.summary = True
-		self.out = sys.stdout # Just until filters get started.
-
-		# Create a bootstrap output system.
-		self.out = filter_list.FilterList()
-
-		if home == None:
-			try:
-				home = os.environ[env]
-			except KeyError:
-				home = os.getcwd()
-
-		# make sure the home directory exists
-		self.home = generic_path.Path(home).Absolute()
-
-		if not self.home.isDir():
-			self.Error("%s '%s' is not a directory", env, self.home)
-			return
-
-		# the set-up file location.
-		# use the override "env2/xml2" if it exists
-		# else use the primary "env/xml" if it exists
-		# else keep the hard-coded defaults.
-		self.raptorXML = self.home.Append(xml)
-
-		if env2 in os.environ:
-			sbs_init = generic_path.Join(os.environ[env2], xml2)
-			if sbs_init.isFile():
-				self.raptorXML = sbs_init
-
-		# things that can be overridden by the set-up file
-		for key, value in defaults.items():
-			self.__dict__[key] = value
-
-		# things to initialise
-		self.args = []
-
-		self.componentGroups = []
-		self.orderComponentGroups = False
-		self.commandlineComponents = []
-
-		self.systemModel = None
-		self.systemDefinitionFile = None
-		self.systemDefinitionRequestedLayers = []
-		self.systemDefinitionOrderLayers = False
-
-		self.specGroups = {}
-
-		self.configNames = []
-		self.configsToBuild = set()
-		self.makeOptions = []
-		self.maker = None
-		self.debugOutput = False
-		self.doExportOnly = False
-		self.noBuild = False
-		self.noDependInclude = False
-		self.projects = set()
-
-		self.cache = raptor_cache.Cache(self)
-		self.override = {env: str(self.home)}
-		self.targets = []
-		self.defaultTargets = []
-
-		self.doCheck = False
-		self.doWhat = False
-		self.doParallelParsing = False
-		self.mission = Raptor.M_BUILD
-
-		# what platform and filesystem are we running on?
-		self.filesystem = raptor_utilities.getOSFileSystem()
-
-		self.toolset = None
-
-		self.starttime = time.time()
-		self.timestring = time.strftime("%Y-%m-%d-%H-%M-%S")
-
-		self.fatalErrorState = False
-
-	def AddConfigList(self, configPathList):
-		# this function converts cmd line option into a list
-		# and prepends it to default config.
-		self.configPath = generic_path.NormalisePathList(configPathList.split(os.pathsep)) + self.configPath
-		return True
-
-	def AddConfigName(self, name):
-		self.configNames.append(name)
-		return True
-
-	def RunQuietly(self, TrueOrFalse):
-		self.quiet = TrueOrFalse
-		return True
-
-	def SetCheck(self, TrueOrFalse):
-		self.doCheck = TrueOrFalse
-		return True
-
-	def SetWhat(self, TrueOrFalse):
-		self.doWhat = TrueOrFalse
-		return True
-
-	def SetEnv(self, name, value):
-		self.override[name] = value
-
-	def AddTarget(self, target):
-		if self.doCheck or self.doWhat:
-			self.Warn("ignoring target %s because --what or --check is specified.\n", target)
-		else:
-			self.targets.append(target)
-			
-	def AddSourceTarget(self, filename):
-		# source targets are sanitised and then added as if they were a "normal" makefile target
-		# in addition they have a default, empty, top-level target assigned in order that they can
-		# be presented to any generated makefile without error
-		sourceTarget = generic_path.Path(filename).Absolute()
-		sourceTarget = 'SOURCETARGET_' + raptor_utilities.sanitise(str(sourceTarget))
-		self.AddTarget(sourceTarget)
-		self.defaultTargets.append(sourceTarget)
-		return True
-
-	def SetSysDefFile(self, filename):
-		self.systemDefinitionFile = generic_path.Path(filename)
-		return True
-
-	def SetSysDefBase(self, path):
-		self.systemDefinitionBase = generic_path.Path(path)
-		return True
-
-	def AddSysDefLayer(self, layer):
-		self.systemDefinitionRequestedLayers.append(layer)
-		return True
-
-	def SetSysDefOrderLayers(self, TrueOrFalse):
-		self.systemDefinitionOrderLayers = TrueOrFalse
-		return True
-
-	def AddBuildInfoFile(self, filename):
-		bldinf = generic_path.Path(filename).Absolute()
-		self.commandlineComponents.append(bldinf)
-		return True
-
-	def SetTopMakefile(self, filename):
-		self.topMakefile = generic_path.Path(filename)
-		return True
-
-	def SetDebugOutput(self, TrueOrFalse):
-		self.debugOutput = TrueOrFalse
-		return True
-
-	def SetExportOnly(self, TrueOrFalse):
-		self.doExportOnly = TrueOrFalse
-		return True
-
-	def SetNoBuild(self, TrueOrFalse):
-		self.noBuild = TrueOrFalse
-		return True
-
-	def SetNoDependInclude(self, TrueOrFalse):
-		self.noDependInclude = TrueOrFalse
-		return True
-		
-	def SetKeepGoing(self, TrueOrFalse):
-		self.keepGoing = TrueOrFalse
-		return True
-
-	def SetLogFileName(self, logfile):
-		if logfile == "-":
-			self.logFileName = None  # stdout
-		else:
-			self.logFileName = generic_path.Path(logfile)
-		return True
-
-	def SetMakeEngine(self, makeEngine):
-		self.makeEngine = makeEngine
-		return True
-
-	def AddMakeOption(self, makeOption):
-		self.makeOptions.append(makeOption)
-		return True
-
-	def SetJobs(self, numberOfJobs):
-		try:
-			self.jobs = int(numberOfJobs)
-		except ValueError:
-			self.jobs = 0
-
-		if self.jobs < 1:
-			self.Warn("The number of jobs (%s) must be a positive integer\n", numberOfJobs)
-			self.jobs = 1
-			return False
-		return True
-
-	def SetTries(self, numberOfTries):
-		try:
-			self.tries = int(numberOfTries)
-		except ValueError:
-			self.tries = 0
-
-		if self.tries < 1:
-			self.Warn("The number of tries (%s) must be a positive integer\n", numberOfTries)
-			self.tries = 1
-			return False
-		return True
-
-	def SetToolCheck(self, type):
-		type = type.lower()
-		toolcheck_types= [ "forced", "on", "off" ]
-		if type in toolcheck_types:
-			self.toolcheck=type
-		else:
-			self.Warn("toolcheck option must be one of: %s" % toolcheck_types)
-			return False
-
-		return True
-
-	def SetParallelParsing(self, type):
-		type = type.lower()
-		if type == "on":
-			self.doParallelParsing = True
-		elif type == "off":
-			self.doParallelParsing = False
-		else:
-			self.Warn(" parallel parsing option must be either 'on' or 'off' (was %s)"  % type)
-			return False
-
-		return True
-
-	def AddProject(self, projectName):
-		self.projects.add(projectName.lower())
-		return True
-
-	def FilterList(self, value):
-		self.filterList = value
-		return True
-
-	def IgnoreOsDetection(self, value):
-		self.ignoreOsDetection = value
-		return True
-
-	def PrintVersion(self,dummy):
-		global name
-		print name, "version", raptor_version.Version()
-		self.mission = Raptor.M_VERSION
-		return False
-
-	# worker methods
-
-	def Introduction(self):
-		"""Print a header of useful information about Raptor"""
-
-		self.Info("%s: version %s\n", name, raptor_version.Version())
-
-		self.Info("%s %s", env, str(self.home))
-		self.Info("Set-up %s", str(self.raptorXML))
-		self.Info("Command-line-arguments %s", " ".join(self.args))
-		self.Info("Current working directory %s", os.getcwd())
-		
-		# the inherited environment
-		for e, value in os.environ.items():
-			self.Info("Environment %s=%s", e, value)
-
-		# and some general debug stuff
-		self.Debug("Platform %s", "-".join(hostplatform))
-		self.Debug("Filesystem %s", self.filesystem)
-		self.Debug("Python %d.%d.%d", *sys.version_info[:3])
-		self.Debug("Command-line-parser %s", self.CLI)
-
-		for e,value in self.override.items():
-			self.Debug("Override %s = %s", e, value)
-
-		for t in self.targets:
-			self.Debug("Target %s", t)
-
-
-	def ConfigFile(self):
-		if not self.raptorXML.isFile():
-			return
-
-		self.cache.Load(self.raptorXML)
-
-		# find the 'defaults.raptor' variant and extract the values
-		try:
-			var = self.cache.FindNamedVariant("defaults.init")
-			evaluator = self.GetEvaluator( None, raptor_data.BuildUnit(var.name,[var]) )
-
-			for key, value in defaults.items():
-				newValue = evaluator.Resolve(key)
-
-				if newValue != None:
-					# got a string for the value
-					if type(value) == types.BooleanType:
-						newValue = (newValue.lower() != "false")
-					elif type(value) == types.IntType:
-						newValue = int(newValue)
-					elif isinstance(value, generic_path.Path):
-						newValue = generic_path.Path(newValue)
-
-					self.__dict__[key] = newValue
-
-		except KeyError:
-			# it is OK to not have this but useful to say it wasn't there
-			self.Info("No 'defaults.init' configuration found in " + str(self.raptorXML))
-
-
-	def CommandLine(self, args):
-		# remember the arguments for the log
-		self.args = args
-
-		# assuming self.CLI = "raptor_cli"
-		more_to_do = raptor_cli.GetArgs(self, args)
-
-		# resolve inter-argument dependencies.
-		# --what or --check implies the WHAT target and FilterWhat Filter
-		if self.doWhat or self.doCheck:
-			self.targets = ["WHAT"]
-			self.filterList = "filterwhat"
-
-		else:
-			# 1. CLEAN/CLEANEXPORT/REALLYCLEAN needs the FilterClean filter.
-			# 2. Targets that clean should not be combined with other targets.
-
-			targets = [x.lower() for x in self.targets]
-
-			CL = "clean"
-			CE = "cleanexport"
-			RC = "reallyclean"
-
-			is_clean = 0
-			is_suspicious_clean = 0
-
-			if CL in targets and CE in targets:
-				is_clean = 1
-				if len(targets) > 2:
-					is_suspicious_clean = 1
-			elif RC in targets or CL in targets or CE in targets:
-				is_clean = 1
-				if len(targets) > 1:
-					is_suspicious_clean = 1
-
-			if is_clean:
-				self.filterList += ",filterclean"
-				if is_suspicious_clean:
-					self.Warn('CLEAN, CLEANEXPORT and a REALLYCLEAN should not be combined with other targets as the result is unpredictable.')
-
-		if not more_to_do:
-			self.skipAll = True		# nothing else to do
-
-	def ProcessConfig(self):
-		# this function will perform additional processing of config
-
-		# create list of generic paths
-		self.configPath = generic_path.NormalisePathList(self.systemConfig.split(os.pathsep))
-
-	def LoadCache(self):
-		def mkAbsolute(aGenericPath):
-			""" internal function to make a generic_path.Path
-			absolute if required"""
-			if not aGenericPath.isAbsolute():
-				return self.home.Append(aGenericPath)
-			else:
-				return aGenericPath
-		
-		# make generic paths absolute (if required)
-		self.configPath = map(mkAbsolute, self.configPath)
-		self.cache.Load(self.configPath)
-
-		if not self.systemFLM.isAbsolute():
-			self.systemFLM = self.home.Append(self.systemFLM)
-
-		self.cache.Load(self.systemFLM)
-
-	def GetConfig(self, configname):
-		names = configname.split(".")
-
-		cache = self.cache
-
-		base = names[0]
-		mods = names[1:]
-
-		if base in cache.groups:
-			x = cache.FindNamedGroup(base)
-		elif base in cache.aliases:
-			x = cache.FindNamedAlias(base)
-		elif base in cache.variants:
-			x = cache.FindNamedVariant(base)
-		else:
-			raise Exception("Unknown build configuration '%s'" % configname)
-
-		x.ClearModifiers()
-
-
-		try:
-			for m in mods: x.AddModifier( cache.FindNamedVariant(m) )
-		except KeyError:
-			raise Exception("Unknown build configuration '%s'" % configname)
-		return x
-
-	def GetBuildUnitsToBuild(self, configNames):
-		"""Return a list of the configuration objects that correspond to the 
-		   list of configuration names in the configNames parameter.
-
-		raptor.GetBuildUnitsToBuild(["armv5", "winscw"])
-		>>> [ config1, config2, ... , configN ]
-		""" 
-
-		if len(configNames) == 0:
-			# use default config
-			if len(self.defaultConfig) == 0:
-				self.Warn("No default configuration name")
-			else:
-				configNames.append(self.defaultConfig)
-
-		buildUnitsToBuild = set()
-
-
-		for c in set(configNames):
-			try:		
-				x = self.GetConfig(c)
-				buildUnitsToBuild.update( x.GenerateBuildUnits() )
-			except Exception, e:
-				self.FatalError(str(e))
-
-		for b in buildUnitsToBuild:
-			self.Info("Buildable configuration '%s'", b.name)
-
-		if len(buildUnitsToBuild) == 0:
-			self.Error("No build configurations given")
-
-		return buildUnitsToBuild
-
-	def CheckToolset(self, evaluator, configname):
-		"""Check the toolset for a particular config, allow other objects access 
-		to the toolset for this build (e.g. the raptor_make class)."""
-		if self.toolset is None:
-			if self.toolcheck == 'on':
-				self.toolset = raptor_data.ToolSet(log=self)
-			elif self.toolcheck == 'forced' :
-				self.toolset = raptor_data.ToolSet(log=self, forced=True)
-			else:
-				return True
-
-		return self.toolset.check(evaluator, configname)
-
-
-	def CheckConfigs(self, configs):
-		"""	Tool checking for all the buildable configurations
-			NB. We are allowed to use different tool versions for different
-			configurations."""
-
-		tools_ok = True
-		for b in configs:
-			self.Debug("Tool check for %s", b.name)
-			evaluator = self.GetEvaluator(None, b, gathertools=True)
-			tools_ok = tools_ok and self.CheckToolset(evaluator, b.name)
-
-		return tools_ok
-
-
-
-	def GatherSysModelLayers(self, systemModel, systemDefinitionRequestedLayers):
-		"""Return a list of lists of components to be built.
-
-		components = GatherSysModelLayers(self, configurations)
-		>>> set("abc/group/bld.inf","def/group/bld.inf, ....")
-		"""
-		layersToBuild = []
-
-		if systemModel:
-			# We either process all available layers in the system model, or a subset of
-			# layers specified on the command line.  In both cases, the processing is the same,
-			# and can be subject to ordering if explicitly requested.
-			systemModel.DumpInfo()
-
-			if systemDefinitionRequestedLayers:
-				layersToProcess = systemDefinitionRequestedLayers
-			else:
-				layersToProcess = systemModel.GetLayerNames()
-
-			for layer in layersToProcess:
-				systemModel.DumpLayerInfo(layer)
-
-				if systemModel.IsLayerBuildable(layer):
-					layersToBuild.append(ComponentGroup(layer,
-							systemModel.GetLayerComponents(layer)))
-
-		return layersToBuild
-
-
-	# Add bld.inf or system definition xml to command line componentGroups (depending on preference)
-	def FindSysDefIn(self, aDir = None):
-		# Find a system definition file
-
-		if aDir is None:
-			dir = generic_path.CurrentDir()
-		else:
-			dir = generic_path.Path(aDir)
-
-		sysDef = dir.Append(self.systemDefinition)
-		if not sysDef.isFile():
-			return None
-
-		return sysDef
-
-
-	def FindComponentIn(self, aDir = None):
-		# look for a bld.inf 
-
-		if aDir is None:
-			dir = generic_path.CurrentDir()
-		else:
-			dir = generic_path.Path(aDir)
-
-		bldInf = dir.Append(self.buildInformation)
-		componentgroup = []
-
-		if bldInf.isFile():
-			return bldInf
-
-		return None
-
-	def AttachSpecs(self, groups):
-		# tell the specs which Raptor object they work for (so that they can
-		# access the cache and issue warnings and errors)
-		for spec in groups:
-			spec.SetOwner(self)
-			self.Info("Buildable specification '%s'", spec.name)
-			if self.debugOutput:
-				spec.DebugPrint()
-
-	def GenerateGenericSpecs(self, configsToBuild):
-		# if a Configuration has any config-wide interfaces
-		# then add a Specification node to call each of them.
-		configWide = {}
-		genericSpecs = []
-		for c in configsToBuild:
-			evaluator = self.GetEvaluator(None, c)
-			iface = evaluator.Get("INTERFACE.config")
-			if iface:
-				if iface in configWide:
-					# seen it already, so reuse the node
-					filter = configWide[iface]
-					filter.AddConfigCondition(c.name)
-				else:
-					# create a new node
-					filter = raptor_data.Filter("config_wide")
-					filter.AddConfigCondition(c.name)
-					for i in iface.split():
-						spec = raptor_data.Specification(i)
-						spec.SetInterface(i)
-						filter.AddChildSpecification(spec)
-					# remember it, use it
-					configWide[iface] = filter
-					genericSpecs.append(filter)
-
-		self.AttachSpecs(genericSpecs)
-
-		return genericSpecs
-
-
-	def WriteMetadataDepsMakefile(self, component_group):
-		""" Takes a list of (filename, target) tuples that indicate where """
-		# Create a Makefile that includes all the dependency information for this spec group
-		build_metamakefile_name = \
-				os.path.abspath(sbs_build_dir).replace('\\','/').rstrip('/') + \
-				'/metadata_%s.mk' % component_group.name.lower()
-		bmkmf = open(build_metamakefile_name, "w+")
-		bmkmf.write("# Build Metamakefile - Dependencies for metadata during the 'previous' build\n\n")
-		bmkmf.write("PARSETARGET:=%s\n" % build_metamakefile_name)
-		bmkmf.write("%s:  \n" % build_metamakefile_name)
-		bmkmf.write("\t@echo -e \"\\nRE-RUNNING SBS with previous parameters\"\n")
-		bmkmf.write("\t@echo pretend-sbs %s\n" % " ".join(self.args))
-		try:
-			for m in component_group.dependencies:
-				filename, target = m
-				bmkmf.write("-include %s\n\n" % filename)
-		finally:
-			bmkmf.close()
-
-		return build_metamakefile_name
-
-
-	def GetEvaluator(self, specification, configuration, gathertools=False):
-		""" this will perform some caching later """
-		return raptor_data.Evaluator(self, specification, configuration, gathertools=gathertools)
-
-
-	def areMakefilesUptodate(self):
-		return False
-
-
-	def Make(self, makefile):
-
-		if self.maker.Make(makefile):
-			self.Info("The make-engine exited successfully.")
-			return True
-		else:
-			self.Error("The make-engine exited with errors.")
-			return False
-
-
-	def Report(self):
-		if self.quiet:
-			return
-
-		self.endtime = time.time()
-		self.runtime = int(0.5 + self.endtime - self.starttime)
-		self.raptor_params.runtime = self.runtime
-		self.Info("Run time %s seconds" % self.runtime)
-
-	def AssertBuildOK(self):
-		"""Raise a BuildCompleteException if no further processing is required
-		"""
-		if self.Skip():
-			raise BuildCompleteException("")
-
-		return True
-
-	def Skip(self):
-		"""Indicate not to perform operation if:
-		   fatalErrorState is set
-		   an error code is set but we're not in keepgoing mode
-		"""
-		return self.fatalErrorState or ((self.errorCode != 0) and (not self.keepGoing))
-
-
-	# log file open/close
-
-	def OpenLog(self):
-		"""Open a log file for the various I/O methods to write to."""
-
-		try:
-			# Find all the raptor plugins and put them into a pluginbox.
-			if not self.systemPlugins.isAbsolute():
-				self.systemPlugins = self.home.Append(self.systemPlugins)
-
-			self.pbox = pluginbox.PluginBox(str(self.systemPlugins))
-
-			self.raptor_params = BuildStats(self)
-
-			# Open the requested plugins using the pluginbox
-			self.out.open(self.raptor_params, self.filterList.split(','), self.pbox)
-
-			# log header
-			self.out.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n")
-
-			namespace = "http://symbian.com/xml/build/log"
-			schema = "http://symbian.com/xml/build/log/1_0.xsd"
-
-			self.out.write("<buildlog sbs_version=\"%s\" xmlns=\"%s\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"%s %s\">\n"
-						   % (raptor_version.Version(), namespace, namespace, schema))
-			self.logOpen = True
-		except Exception,e:
-			self.out = sys.stdout # make sure that we can actually get errors out.
-			self.logOpen = False
-			self.FatalError("Unable to open the output logs: %s" % str(e))
-
-
-	def CloseLog(self):
-		if self.logOpen:
-			self.out.summary()
-			self.out.write("</buildlog>\n")
-
-			if not self.out.close():
-				self.errorCode = 1
-
-
-	def Cleanup(self):
-		# ensure that the toolset cache is flushed.
-		if self.toolset is not None:
-			self.toolset.write()
-
-	# I/O methods
-
-	@staticmethod
-	def attributeString(dictionary):
-		"turn a dictionary into a string of XML attributes"
-		atts = ""
-		for a,v in dictionary.items():
-			atts += " " + a + "='" + v + "'"
-		return atts
-	
-	def Info(self, format, *extras, **attributes):
-		"""Send an information message to the configured channel
-				(XML control characters will be escaped)
-		"""
-		self.out.write("<info" + self.attributeString(attributes) + ">" +
-		               escape(format % extras) + "</info>\n")
-
-	def Debug(self, format, *extras, **attributes):
-		"Send a debugging message to the configured channel"
-
-		# the debug text is out of our control so wrap it in a CDATA
-		# in case it contains characters special to XML... like <>
-		if self.debugOutput:
-			self.out.write("<debug" + self.attributeString(attributes) + ">" +
-			               "><![CDATA[\n" + (format % extras) + "\n]]></debug>\n")
-
-	def Warn(self, format, *extras, **attributes):
-		"""Send a warning message to the configured channel
-				(XML control characters will be escaped)
-		"""
-		self.out.write("<warning" + self.attributeString(attributes) + ">" + 
-		               escape(format % extras) + "</warning>\n")
-
-	def FatalError(self, format, *extras, **attributes):
-		"""Send an error message to the configured channel. This implies such a serious
-		   error that the entire build must be shut down asap whilst still finishing off
-		   correctly whatever housekeeping is possible e.g. producing error reports.
-		   Remains quiet if the raptor object is already in a fatal state since there
-		   further errors are probably triggered by the first.
-		"""
-		if not self.fatalErrorState:
-			self.out.write("<error" + self.attributeString(attributes) + ">" + 
-			               (format % extras) + "</error>\n")
-			self.errorCode = 1
-			self.fatalErrorState = True
-
-	def Error(self, format, *extras, **attributes):
-		"""Send an error message to the configured channel
-				(XML control characters will be escaped)
-		"""
-		self.out.write("<error" + self.attributeString(attributes) + ">" + 
-		               escape(format % extras) + "</error>\n")
-		self.errorCode = 1
-
-
-	def PrintXML(self, format, *extras):
-		"Print to configured channel (no newline is added) (assumes valid xml)"
-		if format:
-			self.out.write(format % extras)
-
-
-	def MakeComponentGroup(self, cg):
-		if not self.maker:
-			self.maker = raptor_make.MakeEngine(self)
-
-		if self.maker == None:
-			self.Error("No make engine present")
-			return None
-
-		makefile = cg.CreateMakefile(self.topMakefile, self.maker, self.systemDefinitionOrderLayers)
-		if (not self.noBuild and makefile is not None) \
-				or self.doParallelParsing:
-			# run the build for a single group of specs
-			self.Make(makefile)
-		else:
-			self.Info("No build performed for %s" % cg.name)
-
-	def GetComponentGroupsFromCLI(self):
-		"""Returns the list of componentGroups as specified by the
-		   commandline interface to Raptor e.g. parameters
-		   or the current directory"""
-		componentGroups=[]
-		# Look for bld.infs or sysdefs in the current dir if none were specified
-		if self.systemDefinitionFile == None and len(self.commandlineComponents) == 0:
-			if not self.preferBuildInfoToSystemDefinition:
-				cwd = os.getcwd()
-				self.systemDefinitionFile = self.FindSysDefIn(cwd)
-				if self.systemDefinitionFile == None:
-					aComponent = self.FindComponentIn(cwd)
-					if aComponent:
-						componentGroups.append(ComponentGroup('default',[aComponent]))
-			else:
-				aComponent = self.FindComponentIn(cwd)
-				if aComponent is None:
-					self.systemDefinitionFile = self.FindSysDefIn(cwd)
-				else:
-					componentGroups.append(ComponentGroup('default',[aComponent]))
-
-			if len(componentGroups) <= 0 and  self.systemDefinitionFile == None:
-				self.Warn("No default bld.inf or system definition file found in current directory (%s)", cwd)
-
-		# If we now have a System Definition to parse then get the layers of components
-		if self.systemDefinitionFile != None:
-			systemModel = raptor_xml.SystemModel(self, self.systemDefinitionFile, self.systemDefinitionBase)
-			componentGroups = self.GatherSysModelLayers(systemModel, self.systemDefinitionRequestedLayers)
-			
-		# Now get components specified on a commandline - build them after any
-		# layers in the system definition.
-		if len(self.commandlineComponents) > 0:
-			componentGroups.append(ComponentGroup('commandline',self.commandlineComponents))
-
-		# If we aren't building components in order then flatten down
-		# the groups
-		if not self.systemDefinitionOrderLayers:
-			# Flatten the layers into one group of components if
-			# we are not required to build them in order.
-			newcg = ComponentGroup("all")
-			for cg in componentGroups:
-				newcg.extend(cg)
-			componentGroups = [newcg]
-
-		return componentGroups
-
-	def Build(self):
-
-		if self.mission != Raptor.M_BUILD: # help or version requested instead.
-			return 0
-
-		# open the log file
-		self.OpenLog()
-
-
-		try:
-			# show the command and platform info
-			self.AssertBuildOK()
-			self.Introduction()
-			# establish an object cache
-			self.AssertBuildOK()
-			
-			self.LoadCache()
-
-			# find out what configurations to build
-			self.AssertBuildOK()
-			buildUnitsToBuild = set()
-			buildUnitsToBuild = self.GetBuildUnitsToBuild(self.configNames)
-
-			# find out what components to build, and in what way
-			componentGroups = []
-
-			self.AssertBuildOK()
-			if len(buildUnitsToBuild) >= 0:
-				componentGroups = self.GetComponentGroupsFromCLI()
-
-			componentCount = reduce(lambda x,y : x + y, [len(cg) for cg in componentGroups])
-
-			if not componentCount > 0:
-				raise BuildCompleteException("No components to build.")
-
-			# check the configurations (tools versions)
-			self.AssertBuildOK()
-
-			if self.toolcheck != 'off':
-				self.CheckConfigs(buildUnitsToBuild)
-			else:
-				self.Info(" Not Checking Tool Versions")
-
-			self.AssertBuildOK()
-
-
-			# if self.doParallelParsing and not (len(componentGroups) == 1 and len(componentGroups[0]) == 1):
-			if self.doParallelParsing:
-				# Create a Makefile to parse components in parallel and build them
-				for cg in componentGroups:
-					cg.GenerateMetadataSpecs(buildUnitsToBuild)
-					self.MakeComponentGroup(cg)
-				if self.noBuild:
-					self.Info("No build performed")
-			else:
-				# Parse components serially, creating one set of makefiles
-				# create non-component specs
-				self.AssertBuildOK()
-				generic_specs = self.GenerateGenericSpecs(buildUnitsToBuild)
-
-				self.AssertBuildOK()
-				for cg in componentGroups:
-					# create specs for a specific group of components
-					cg.GenerateSpecs(generic_specs, buildUnitsToBuild)
-					self.WriteMetadataDepsMakefile(cg)	
-					
-					# generate the makefiles for one group of specs
-					self.MakeComponentGroup(cg)
-
-		except BuildCompleteException,b:
-			if str(b) != "":
-				self.Info(str(b))
-
-		# final report
-		if not self.fatalErrorState:
-			self.Report()
-
-		self.Cleanup()
-
-		# close the log file
-		self.CloseLog()
-
-		return self.errorCode
-
-	@classmethod
-	def CreateCommandlineBuild(cls, argv):
-		""" Perform a 'typical' build. """
-		# configure the framework
-
-		build = Raptor()
-		build.AssertBuildOK()
-		build.ConfigFile()
-		build.ProcessConfig()
-		build.CommandLine(argv)
-
-		return build 
-
-
-
-# Class for passing constricted parameters to filters
-class BuildStats(object):
-
-	def __init__(self, raptor_instance):
-		self.logFileName = raptor_instance.logFileName
-		self.quiet = raptor_instance.quiet
-		self.doCheck = raptor_instance.doCheck
-		self.doWhat = raptor_instance.doWhat
-		self.platform = hostplatform
-		self.skipAll = raptor_instance.fatalErrorState
-		self.timestring = raptor_instance.timestring
-		self.targets = raptor_instance.targets
-		self.runtime = 0
-		self.name = name
-
-
-# raptor module functions
-
-def Main(argv):
-	"""The main entry point for Raptor.
-
-	argv is a list of command-line parameters,
-	NOT including the name of the calling script.
-
-	The return value is zero for success and non-zero for failure."""
-
-	DisplayBanner()
-
-	# object which represents a build
-	b = Raptor.CreateCommandlineBuild(argv)
-
-	# allow all objects to log to the
-	# build they're being used in
-	global build
-	global log
-	build = b
-	log = b
-
-
-	result = b.Build()
-
-	return result
-
-
-def DisplayBanner():
-	"""Stuff that needs printing out for every command."""
-	pass
-
-
-
-# end of the raptor module
+#
+# 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:
+# raptor module
+# This module represents the running Raptor program. Raptor is started
+# either by calling the Main() function, which creates an instance of
+# the raptor.Raptor class and calls its methods to perform a build based
+# on command-line parameters, or by explicitly creating a raptor.Raptor
+# instance and calling its methods to set-up and perform a build.
+#
+
+name = "sbs"			# the public name for the raptor build tool
+env  = "SBS_HOME"		# the environment variable that locates us
+xml  = "sbs_init.xml"	# the primary initialisation file
+env2 = "HOME"		 	# the environment variable that locates the user
+xml2 = ".sbs_init.xml"	# the override initialisation file
+
+import generic_path
+import os
+import raptor_cache
+import raptor_cli
+import raptor_data
+import raptor_make
+import raptor_makefile
+import raptor_meta
+import raptor_timing
+import raptor_utilities
+import raptor_version
+import raptor_xml
+import filter_list
+import sys
+import types
+import time
+import traceback
+import pluginbox
+from xml.sax.saxutils import escape
+
+
+if not "HOSTPLATFORM" in os.environ or not "HOSTPLATFORM_DIR" in os.environ:
+	print "Error: HOSTPLATFORM and HOSTPLATFORM_DIR must be set in the environment (this is usually done automatically by the startup script)."
+	sys.exit(1)
+
+hostplatform = os.environ["HOSTPLATFORM"].split(" ")
+hostplatform_dir = os.environ["HOSTPLATFORM_DIR"]
+
+# defaults can use EPOCROOT
+
+if "EPOCROOT" in os.environ:
+	incoming_epocroot = os.environ["EPOCROOT"]
+	epocroot = incoming_epocroot.replace("\\","/")
+else:
+	if 'win' in hostplatform:
+		incoming_epocroot = os.sep
+		epocroot = "/"
+		os.environ["EPOCROOT"] = os.sep
+	else:
+		epocroot=os.environ['HOME'] + os.sep + "epocroot"
+		os.environ["EPOCROOT"] = epocroot
+		incoming_epocroot = epocroot
+
+if "SBS_BUILD_DIR" in os.environ:
+	sbs_build_dir = os.environ["SBS_BUILD_DIR"]
+else:
+	sbs_build_dir = (epocroot + "/epoc32/build").replace("//","/")
+
+
+# only use default XML from the epoc32 tree if it exists
+defaultSystemConfig = "lib/config"
+epoc32UserConfigDir = generic_path.Join(epocroot, "epoc32/sbs_config")
+if epoc32UserConfigDir.isDir():
+	defaultSystemConfig = str(epoc32UserConfigDir) + os.pathsep + defaultSystemConfig
+
+# parameters that can be overriden by the sbs_init.xml file
+# or by the command-line.
+defaults = {
+		"allowCommandLineOverrides" : True,
+		"CLI" : "raptor_cli",
+		"buildInformation" : generic_path.Path("bld.inf"),
+		"defaultConfig" : "default",
+		"jobs": 4,
+		"keepGoing": False,
+		"logFileName" : generic_path.Join(sbs_build_dir,"Makefile.%TIME.log"),
+		"makeEngine" : "make",
+		"preferBuildInfoToSystemDefinition" : False,
+		"pruneDuplicateMakefiles": True,
+		"quiet" : False,
+		"systemConfig" :  defaultSystemConfig,
+		"systemDefinition" : generic_path.Path("System_Definition.xml"),
+		"systemDefinitionBase" : generic_path.Path("."),
+		"systemFLM" : generic_path.Path("lib/flm"),
+		"systemPlugins" : generic_path.Path("python/plugins"),
+		"topMakefile" : generic_path.Join(sbs_build_dir,"Makefile"),
+		"tries": 1,
+		"writeSingleMakefile": True,
+		"ignoreOsDetection": False,
+		"toolcheck": "on",
+		"filterList": "filterterminal,filterlogfile"
+		}
+
+
+
+class ModelNode(object):
+	""" Represents any node in a a tree of build information
+	    e.g. a tree of bld.infs, mmps and finally things like resource blocks and string table blocks.
+	    This is before they are produced into "build" specs.
+	"""
+
+	def __init__(self, id, parent = None):
+		self.id = id
+		self.type = type
+		self.specs = []
+		self.deps = []
+		self.children = set()
+		self.unfurled = False
+		self.parent = parent
+
+	# Allow one to make a set
+	def __hash__(self):
+		return hash(self.id)
+
+	def __cmp__(self,other):
+		return cmp(self.id, other)
+
+	def __iter__(self):
+		return iter(self.children)
+
+	def __getitem__(self,x):
+		if isinstance(x, slice):
+			return self.children[x.start:x.stop]
+		return self.children[x]
+
+	def __setitem__(self,k, v):
+		self.children[k] = v
+
+	def __len__(self):
+		return len(self.children)
+
+	def add(self, item):
+		return self.children.add(item)
+
+	def isunfurled(self, c):
+		return self.unfurled == False
+
+	def unfurl(self, build):
+		"""Find any children of this node by processing it, produces specs"""
+		pass
+
+	def unfurl_all(self, build):
+		"""Unfurl self and all children - preparatory e.g for realisation"""
+		if not self.unfurled:
+			self.unfurl(build)
+
+		self.realise_exports(build) # permit communication of dependencies between children
+
+		for c in self.children:
+			c.unfurl_all(build)
+
+
+	def realise_exports(self, build):
+		"""Do the things that are needed such that we can fully unfurl all
+		   sibling nodes.  i.e. this step is here to "take care" of the dependencies
+		   between siblings.
+		"""
+		pass
+
+	def realise_makefile(self, build, specs):
+		makefilename_base = build.topMakefile
+		if self.name is not None:
+			makefile = generic_path.Path(str(makefilename_base) + "_" + raptor_utilities.sanitise(self.name))
+		else:
+			makefile = generic_path.Path(str(makefilename_base))
+
+		# insert the start time into the Makefile name?
+		makefile.path = makefile.path.replace("%TIME", build.timestring)
+
+		build.InfoDiscovery(object_type = "layers", count = 1)
+		build.InfoStartTime(object_type = "layer", task = "parse",
+				key = str(makefile.path))
+		makefileset = build.maker.Write(makefile, specs, build.buildUnitsToBuild)
+		build.InfoEndTime(object_type = "layer", task = "parse",
+				key = str(makefile.path))
+
+		return makefileset
+
+
+
+	def realise(self, build):
+		"""Give the spec trees to the make engine and actually
+		"build" the product represented by this model node"""
+		# Must ensure that all children are unfurled at this point
+		self.unfurl_all(build)
+
+		sp = self.specs
+
+		build.AssertBuildOK()
+
+		m = self.realise_makefile(build, sp)
+
+		build.InfoStartTime(object_type = "layer", task = "build",
+				key = (str(m.directory) + "/" + str(m.filenamebase)))
+		result = build.Make(m)
+		build.InfoEndTime(object_type = "layer", task = "build",
+				key = (str(m.directory) + "/" + str(m.filenamebase)))
+
+
+		return result
+
+
+
+class Project(ModelNode):
+	"""A project or, in symbian-speak, an MMP
+	"""
+	def __init__(self, filename, parent = None):
+		super(Project,self).__init__(filename, parent = parent)
+		# Assume that components are specified in mmp files for now
+		# One day that tyranny might end.
+		self.mmp_name = str(generic_path.Path.Absolute(filename))
+		self.id = self.mmp_name
+		self.unfurled = False
+
+	def makefile(self, makefilename_base, engine, named = False):
+		"""Makefiles for individual mmps not feasible at the moment"""
+		pass 
+		# Cannot, currently, "unfurl an mmp" directly but do want
+		# to be able to simulate the overall recursive unfurling of a build.
+
+class Component(ModelNode):
+	"""A group of projects or, in symbian-speak, a bld.inf.
+	"""
+	def __init__(self, filename, layername="", componentname=""):
+		super(Component,self).__init__(filename)
+		# Assume that components are specified in bld.inf files for now
+		# One day that tyranny might end.
+		self.bldinf = None # Slot for a bldinf object if we spot one later
+		self.bldinf_filename = generic_path.Path.Absolute(filename)
+
+		self.id = str(self.bldinf_filename)
+		self.exportspecs = []
+		self.depfiles = []
+		self.unfurled = False # We can parse this
+		
+		# Extra metadata optionally supplied with system definition file gathered components
+		self.layername = layername
+		self.componentname = componentname
+
+	def AddMMP(self, filename):
+		self.children.add(Project(filename))
+
+
+class Layer(ModelNode):
+	""" Some components that should be built togther
+		e.g. a Layer in the system definition.
+		
+		Components that come from system definition files can
+		have extra surrounding metadata that we need to pass
+		on for use in log output.
+	"""
+	def __init__(self, name, componentlist=[]):
+		super(Layer,self).__init__(name)
+		self.name = name
+
+		for c in componentlist:
+			if isinstance(c, raptor_xml.SystemModelComponent):
+				# this component came from a system_definition.xml
+				self.children.add(Component(c, c.GetContainerName("layer"), c.GetContainerName("component")))
+			else:
+				# this is a plain old bld.inf file from the command-line
+				self.children.add(Component(c))
+
+	def unfurl(self, build):
+		"""Discover the children of this layer. This involves parsing the component MetaData (bld.infs, mmps).
+		Takes a raptor object as a parameter (build), together with a list of Configurations.
+
+		We currently have parsers that work on collections of components/bld.infs and that cannot
+		parse at a "finer" level.  So one can't 'unfurl' an mmp at the moment.
+
+		Returns True if the object was successfully unfurled.
+		"""
+
+		# setup all our components
+		for c in self.children:
+			c.specs = []
+
+		self.configs = build.buildUnitsToBuild
+
+
+		metaReader = None
+		if len (self.children):
+			try:
+				# create a MetaReader that is aware of the list of
+				# configurations that we are trying to build.
+				metaReader = raptor_meta.MetaReader(build, build.buildUnitsToBuild)
+
+				# convert the list of bld.inf files into a specification
+				# hierarchy suitable for all the configurations we are using.
+				self.specs = list(build.generic_specs)
+				self.specs.extend(metaReader.ReadBldInfFiles(self.children, doexport = build.doExport, dobuild = not build.doExportOnly))
+
+			except raptor_meta.MetaDataError, e:
+				build.Error(e.Text)
+
+		self.unfurled = True
+
+
+	def meta_realise(self, build):
+		"""Generate specs that can be used to "take care of" finding out more
+		about this metaunit - i.e. one doesn't want to parse it immediately
+		but to create a makefile that will parse it.
+		In this case it allows bld.infs to be parsed in parallel by make."""
+
+		# insert the start time into the Makefile name?
+
+		self.configs = build.buildUnitsToBuild
+
+		# Pass certain CLI flags through to the makefile-generating sbs calls
+		cli_options = ""
+
+		if build.debugOutput == True:
+			cli_options += " -d"
+
+		if build.ignoreOsDetection == True:
+			cli_options += " -i"
+
+		if build.keepGoing == True:
+			cli_options += " -k"
+
+		if build.quiet == True:
+			cli_options += " -q"
+
+		if build.noDependInclude == True:
+			cli_options += " --no-depend-include"
+
+		if build.noDependGenerate == True:
+			cli_options += " --no-depend-generate"
+
+
+		nc = len(self.children)
+		number_blocks = build.jobs
+		block_size = (nc / number_blocks) + 1
+		component_blocks = []
+		spec_nodes = []
+
+		b = 0
+		childlist = list(self.children)
+		while b < nc:
+			component_blocks.append(childlist[b:b+block_size])
+			b += block_size
+
+		while len(component_blocks[-1]) <= 0:
+			component_blocks.pop()
+			number_blocks -= 1
+
+		build.Info("Parallel Parsing: bld.infs split into %d blocks\n", number_blocks)
+		# Cause the binding makefiles to have the toplevel makefile's
+		# name.  The bindee's have __pp appended.
+		tm = build.topMakefile.Absolute()
+		binding_makefiles = raptor_makefile.MakefileSet(str(tm.Dir()), build.maker.selectors, makefiles=None, filenamebase=str(tm.File()))
+		build.topMakefile = generic_path.Path(str(build.topMakefile) + "_pp")
+
+		loop_number = 0
+		for block in component_blocks:
+			loop_number += 1
+			specNode = raptor_data.Specification("metadata_" + self.name)
+
+			componentList = " ".join([str(c.bldinf_filename) for c in block])
+
+
+			configList = " ".join([c.name for c in self.configs if c.name != "build" ])
+
+			makefile_path = str(build.topMakefile) + "_" + str(loop_number)
+			try:
+				os.unlink(makefile_path) # until we have dependencies working properly
+			except Exception:
+				pass
+
+			# add some basic data in a component-wide variant
+			var = raptor_data.Variant()
+			var.AddOperation(raptor_data.Set("COMPONENT_PATHS", componentList))
+			var.AddOperation(raptor_data.Set("MAKEFILE_PATH", makefile_path))
+			var.AddOperation(raptor_data.Set("CONFIGS", configList))
+			var.AddOperation(raptor_data.Set("CLI_OPTIONS", cli_options))
+
+
+			# Allow the flm to skip exports. Note: this parameter
+			doexport_str = '1'
+			if not build.doExport:
+				doexport_str = ''
+			var.AddOperation(raptor_data.Set("DOEXPORT", doexport_str ))
+
+			# Pass on '-n' (if specified) to the makefile-generating sbs calls
+			if build.noBuild:
+				var.AddOperation(raptor_data.Set("NO_BUILD", "1"))
+			specNode.AddVariant(var)
+
+			try:
+				interface = build.cache.FindNamedInterface("build.makefiles")
+				specNode.SetInterface(interface)
+			except KeyError:
+				build.Error("Can't find flm interface 'build.makefiles' ")
+
+			spec_nodes.append(specNode)
+			binding_makefiles.addInclude(str(makefile_path)+"_all")
+
+		build.InfoDiscovery(object_type = "layers", count = 1)
+		build.InfoStartTime(object_type = "layer", task = "parse",
+				key = str(build.topMakefile))
+		m = self.realise_makefile(build, spec_nodes)
+		m.close()
+		gen_result = build.Make(m)
+
+		build.InfoEndTime(object_type = "layer", task = "parse",
+				key = str(build.topMakefile))
+		build.InfoStartTime(object_type = "layer", task = "build",
+				key = str(build.topMakefile))
+		build.Debug("Binding Makefile base name is %s ", binding_makefiles.filenamebase)
+		binding_makefiles.close()
+		b = build.Make(binding_makefiles)
+		build.InfoEndTime(object_type = "layer", task = "build",
+				key = str(build.topMakefile))
+		return b
+
+
+
+
+class BuildCannotProgressException(Exception):
+	pass
+
+# raptor module classes
+
+class Raptor(object):
+	"""An instance of a running Raptor program.
+
+	When operated from the command-line there is a single Raptor object
+	created by the Main function. When operated by an IDE several Raptor
+	objects may be created and operated at the same time."""
+
+	# mission enumeration
+	M_BUILD = 1
+	M_QUERY = 2
+	M_VERSION = 3
+
+	def __init__(self, home = None):
+
+		self.DefaultSetUp(home)
+
+
+	def DefaultSetUp(self, home = None):
+		"revert to the default set-up state"
+		self.errorCode = 0
+		self.skipAll = False
+		self.summary = True
+		self.out = sys.stdout # Just until filters get started.
+
+		# Create a bootstrap output system.
+		self.out = filter_list.FilterList()
+
+		if home == None:
+			try:
+				home = os.environ[env]
+			except KeyError:
+				home = os.getcwd()
+
+		# make sure the home directory exists
+		self.home = generic_path.Path(home).Absolute()
+
+		if not self.home.isDir():
+			self.Error("%s '%s' is not a directory", env, self.home)
+			return
+
+		# the set-up file location.
+		# use the override "env2/xml2" if it exists
+		# else use the primary "env/xml" if it exists
+		# else keep the hard-coded defaults.
+		self.raptorXML = self.home.Append(xml)
+
+		if env2 in os.environ:
+			sbs_init = generic_path.Join(os.environ[env2], xml2)
+			if sbs_init.isFile():
+				self.raptorXML = sbs_init
+
+		# things that can be overridden by the set-up file
+		for key, value in defaults.items():
+			self.__dict__[key] = value
+
+		# things to initialise
+		self.args = []
+
+		self.layers = []
+		self.orderLayers = False
+		self.commandlineComponents = []
+
+		self.systemModel = None
+		self.systemDefinitionFile = None
+		self.systemDefinitionRequestedLayers = []
+		self.systemDefinitionOrderLayers = False
+
+		self.specGroups = {}
+
+		self.configNames = []
+		self.configsToBuild = set()
+		self.makeOptions = []
+		self.maker = None
+		self.debugOutput = False
+		self.doExportOnly = False
+		self.doExport = True
+		self.noBuild = False
+		self.noDependInclude = False
+		self.noDependGenerate = False
+		self.projects = set()
+		self.queries = []
+		
+		self.cache = raptor_cache.Cache(self)
+		self.override = {env: str(self.home)}
+		self.targets = []
+		self.defaultTargets = []
+
+		self.doCheck = False
+		self.doWhat = False
+		self.doParallelParsing = False
+		self.mission = Raptor.M_BUILD
+
+		# what platform and filesystem are we running on?
+		self.filesystem = raptor_utilities.getOSFileSystem()
+
+		self.timing = True # Needed by filters such as copy_file to monitor progress
+		self.toolset = None
+
+		self.starttime = time.time()
+		self.timestring = time.strftime("%Y-%m-%d-%H-%M-%S")
+
+		self.fatalErrorState = False
+
+	def AddConfigList(self, configPathList):
+		# this function converts cmd line option into a list
+		# and prepends it to default config.
+		self.configPath = generic_path.NormalisePathList(configPathList.split(os.pathsep)) + self.configPath
+		return True
+
+	def AddConfigName(self, name):
+		if name == "build":
+			traceback.print_stack((sys.stdout))
+			sys.exit(1)
+		self.configNames.append(name)
+		return True
+
+	def RunQuietly(self, TrueOrFalse):
+		self.quiet = TrueOrFalse
+		return True
+
+	def SetCheck(self, TrueOrFalse):
+		self.doCheck = TrueOrFalse
+		return True
+
+	def SetWhat(self, TrueOrFalse):
+		self.doWhat = TrueOrFalse
+		return True
+
+	def SetEnv(self, name, value):
+		self.override[name] = value
+
+	def AddTarget(self, target):
+		if self.doCheck or self.doWhat:
+			self.Warn("ignoring target %s because --what or --check is specified.\n", target)
+		else:
+			self.targets.append(target)
+
+	def AddSourceTarget(self, filename):
+		# source targets are sanitised and then added as if they were a "normal" makefile target
+		# in addition they have a default, empty, top-level target assigned in order that they can
+		# be presented to any generated makefile without error
+		sourceTarget = generic_path.Path(filename).Absolute()
+		sourceTarget = 'SOURCETARGET_' + raptor_utilities.sanitise(str(sourceTarget))
+		self.AddTarget(sourceTarget)
+		self.defaultTargets.append(sourceTarget)
+		return True
+
+	def SetSysDefFile(self, filename):
+		self.systemDefinitionFile = generic_path.Path(filename)
+		return True
+
+	def SetSysDefBase(self, path):
+		self.systemDefinitionBase = generic_path.Path(path)
+		return True
+
+	def AddSysDefLayer(self, layer):
+		self.systemDefinitionRequestedLayers.append(layer)
+		return True
+
+	def SetSysDefOrderLayers(self, TrueOrFalse):
+		self.systemDefinitionOrderLayers = TrueOrFalse
+		return True
+
+	def AddBuildInfoFile(self, filename):
+		bldinf = generic_path.Path(filename).Absolute()
+		self.commandlineComponents.append(bldinf)
+		return True
+
+	def SetTopMakefile(self, filename):
+		self.topMakefile = generic_path.Path(filename)
+		return True
+
+	def SetDebugOutput(self, TrueOrFalse):
+		self.debugOutput = TrueOrFalse
+		return True
+
+	def SetExportOnly(self, TrueOrFalse):
+		self.doExportOnly = TrueOrFalse
+		if not self.doExport:
+			self.Error("The --noexport and --export-only options are incompatible - won't to do anything useful")
+			return False
+		return True
+
+	def SetNoExport(self, TrueOrFalse):
+		self.doExport = not TrueOrFalse
+		if self.doExportOnly:
+			self.Error("The --noexport and --export-only options are incompatible - won't to do anything useful")
+			return False
+		return True
+
+	def SetNoBuild(self, TrueOrFalse):
+		self.noBuild = TrueOrFalse
+		return True
+
+	def SetNoDependInclude(self, TrueOrFalse):
+		self.noDependInclude = TrueOrFalse
+		return True
+
+	def SetNoDependGenerate(self, TrueOrFalse):
+		self.noDependGenerate = TrueOrFalse
+		return True
+
+	def SetKeepGoing(self, TrueOrFalse):
+		self.keepGoing = TrueOrFalse
+		return True
+
+	def SetLogFileName(self, logfile):
+		if logfile == "-":
+			self.logFileName = None  # stdout
+		else:
+			self.logFileName = generic_path.Path(logfile)
+		return True
+
+	def SetMakeEngine(self, makeEngine):
+		self.makeEngine = makeEngine
+		return True
+
+	def AddMakeOption(self, makeOption):
+		self.makeOptions.append(makeOption)
+		return True
+
+	def SetJobs(self, numberOfJobs):
+		try:
+			self.jobs = int(numberOfJobs)
+		except ValueError:
+			self.jobs = 0
+
+		if self.jobs < 1:
+			self.Warn("The number of jobs (%s) must be a positive integer\n", numberOfJobs)
+			self.jobs = 1
+			return False
+		return True
+
+	def SetTries(self, numberOfTries):
+		try:
+			self.tries = int(numberOfTries)
+		except ValueError:
+			self.tries = 0
+
+		if self.tries < 1:
+			self.Warn("The number of tries (%s) must be a positive integer\n", numberOfTries)
+			self.tries = 1
+			return False
+		return True
+
+	def SetToolCheck(self, type):
+		type = type.lower()
+		toolcheck_types= [ "forced", "on", "off" ]
+		if type in toolcheck_types:
+			self.toolcheck=type
+		else:
+			self.Warn("toolcheck option must be one of: %s" % toolcheck_types)
+			return False
+
+		return True
+
+	def SetTiming(self, TrueOrFalse):
+		self.Info("--timing switch no longer has any effect - build timing is now permanently on")
+		return True
+
+	def SetParallelParsing(self, type):
+		type = type.lower()
+		if type == "on":
+			self.doParallelParsing = True
+		elif type == "slave":
+			self.isParallelParsingSlave = True
+		elif type == "off":
+			self.doParallelParsing = False
+		else:
+			self.Warn(" parallel parsing option must be either 'on' or 'off' (was %s)"  % type)
+			return False
+
+		return True
+
+	def AddProject(self, projectName):
+		self.projects.add(projectName.lower())
+		return True
+
+	def AddQuery(self, q):
+		self.queries.append(q)
+		self.mission = Raptor.M_QUERY
+		return True
+	
+	def FilterList(self, value):
+		self.filterList = value
+		return True
+
+	def IgnoreOsDetection(self, value):
+		self.ignoreOsDetection = value
+		return True
+
+	def PrintVersion(self,dummy):
+		global name
+		print name, "version", raptor_version.fullversion()
+		self.mission = Raptor.M_VERSION
+		return False
+
+	# worker methods
+
+	def Introduction(self):
+		"""Print a header of useful information about Raptor"""
+
+		self.Info("%s: version %s\n", name, raptor_version.fullversion())
+
+		self.Info("%s %s", env, str(self.home))
+		self.Info("Set-up %s", str(self.raptorXML))
+		self.Info("Command-line-arguments %s", " ".join(self.args))
+		self.Info("Current working directory %s", os.getcwd())
+
+		# the inherited environment
+		for e, value in sorted( os.environ.items() ):
+			self.Info("Environment %s=%s", e, value.replace("]]>", "]]&gt;"))
+
+		# and some general debug stuff
+		self.Debug("Platform %s", "-".join(hostplatform))
+		self.Debug("Filesystem %s", self.filesystem)
+		self.Debug("Python %d.%d.%d", *sys.version_info[:3])
+		self.Debug("Command-line-parser %s", self.CLI)
+
+		for e,value in self.override.items():
+			self.Debug("Override %s = %s", e, value)
+
+		for t in self.targets:
+			self.Debug("Target %s", t)
+
+
+	def ConfigFile(self):
+		if not self.raptorXML.isFile():
+			return
+
+		self.cache.Load(self.raptorXML)
+
+		# find the 'defaults.raptor' variant and extract the values
+		try:
+			var = self.cache.FindNamedVariant("defaults.init")
+			evaluator = self.GetEvaluator( None, raptor_data.BuildUnit(var.name,[var]) )
+
+			for key, value in defaults.items():
+				newValue = evaluator.Resolve(key)
+
+				if newValue != None:
+					# got a string for the value
+					if type(value) == types.BooleanType:
+						newValue = (newValue.lower() != "false")
+					elif type(value) == types.IntType:
+						newValue = int(newValue)
+					elif isinstance(value, generic_path.Path):
+						newValue = generic_path.Path(newValue)
+
+					self.__dict__[key] = newValue
+
+		except KeyError:
+			# it is OK to not have this but useful to say it wasn't there
+			self.Info("No 'defaults.init' configuration found in " + str(self.raptorXML))
+
+
+	def CommandLine(self, args):
+		# remember the arguments for the log
+		self.args = args
+
+		# assuming self.CLI = "raptor_cli"
+		more_to_do = raptor_cli.GetArgs(self, args)
+
+		# resolve inter-argument dependencies.
+		# --what or --check implies the WHAT target and FilterWhat Filter
+		if self.doWhat or self.doCheck:
+			self.targets = ["WHAT"]
+			self.filterList = "filterwhat"
+
+		else:
+			# 1. CLEAN/CLEANEXPORT/REALLYCLEAN needs the FilterClean filter.
+			# 2. Targets that clean should not be combined with other targets.
+
+			targets = [x.lower() for x in self.targets]
+
+			CL = "clean"
+			CE = "cleanexport"
+			RC = "reallyclean"
+
+			is_clean = 0
+			is_suspicious_clean = 0
+
+			if CL in targets and CE in targets:
+				is_clean = 1
+				if len(targets) > 2:
+					is_suspicious_clean = 1
+			elif RC in targets or CL in targets or CE in targets:
+				is_clean = 1
+				if len(targets) > 1:
+					is_suspicious_clean = 1
+
+			if is_clean:
+				self.filterList += ",filterclean"
+				if is_suspicious_clean:
+					self.Warn('CLEAN, CLEANEXPORT and a REALLYCLEAN should not be combined with other targets as the result is unpredictable.')
+			else:
+				""" Copyfile implements the <copy> tag which is primarily useful with cluster builds.
+				    It allows file copying to occur on the primary build host rather than on the cluster.
+				    This is more efficient.
+				"""
+				self.filterList += ",filtercopyfile"
+
+		if not more_to_do:
+			self.skipAll = True		# nothing else to do
+
+	def ProcessConfig(self):
+		# this function will perform additional processing of config
+
+		# create list of generic paths
+		self.configPath = generic_path.NormalisePathList(self.systemConfig.split(os.pathsep))
+
+	def LoadCache(self):
+		def mkAbsolute(aGenericPath):
+			""" internal function to make a generic_path.Path
+			absolute if required"""
+			if not aGenericPath.isAbsolute():
+				return self.home.Append(aGenericPath)
+			else:
+				return aGenericPath
+
+		# make generic paths absolute (if required)
+		self.configPath = map(mkAbsolute, self.configPath)
+		self.cache.Load(self.configPath)
+
+		if not self.systemFLM.isAbsolute():
+			self.systemFLM = self.home.Append(self.systemFLM)
+
+		self.cache.Load(self.systemFLM)
+
+	def GetBuildUnitsToBuild(self, configNames):
+		"""Return a list of the configuration objects that correspond to the
+		   list of configuration names in the configNames parameter.
+
+		raptor.GetBuildUnitsToBuild(["armv5", "winscw"])
+		>>> [ config1, config2, ... , configN ]
+		"""
+
+		if len(configNames) == 0:
+			# use default config
+			if len(self.defaultConfig) == 0:
+				self.Warn("No default configuration name")
+			else:
+				configNames.append(self.defaultConfig)
+
+		buildUnitsToBuild = raptor_data.GetBuildUnits(configNames, self.cache, self)
+
+		for b in buildUnitsToBuild:
+			self.Info("Buildable configuration '%s'", b.name)
+
+		if len(buildUnitsToBuild) == 0:
+			self.Error("No build configurations given")
+
+		return buildUnitsToBuild
+
+	def CheckToolset(self, evaluator, configname):
+		"""Check the toolset for a particular config, allow other objects access
+		to the toolset for this build (e.g. the raptor_make class)."""
+		if self.toolset is None:
+			if self.toolcheck == 'on':
+				self.toolset = raptor_data.ToolSet(log=self)
+			elif self.toolcheck == 'forced' :
+				self.toolset = raptor_data.ToolSet(log=self, forced=True)
+			else:
+				return True
+
+		return self.toolset.check(evaluator, configname)
+
+
+	def CheckConfigs(self, configs):
+		"""	Tool checking for all the buildable configurations
+			NB. We are allowed to use different tool versions for different
+			configurations."""
+
+		tools_ok = True
+		for b in configs:
+			self.Debug("Tool check for %s", b.name)
+			evaluator = self.GetEvaluator(None, b, gathertools=True)
+			tools_ok = tools_ok and self.CheckToolset(evaluator, b.name)
+
+		return tools_ok
+
+
+
+	def GatherSysModelLayers(self, systemModel, systemDefinitionRequestedLayers):
+		"""Return a list of lists of components to be built.
+
+		components = GatherSysModelLayers(self, configurations)
+		>>> set("abc/group/bld.inf","def/group/bld.inf, ....")
+		"""
+		layersToBuild = []
+
+		if systemModel:
+			# We either process all available layers in the system model, or a subset of
+			# layers specified on the command line.  In both cases, the processing is the same,
+			# and can be subject to ordering if explicitly requested.
+			systemModel.DumpInfo()
+
+			if systemDefinitionRequestedLayers:
+				layersToProcess = systemDefinitionRequestedLayers
+			else:
+				layersToProcess = systemModel.GetLayerNames()
+
+			for layer in layersToProcess:
+				systemModel.DumpLayerInfo(layer)
+
+				if systemModel.IsLayerBuildable(layer):
+					layersToBuild.append(Layer(layer,
+							systemModel.GetLayerComponents(layer)))
+
+		return layersToBuild
+
+
+	# Add bld.inf or system definition xml to command line layers (depending on preference)
+	def FindSysDefIn(self, aDir = None):
+		# Find a system definition file
+
+		if aDir is None:
+			dir = generic_path.CurrentDir()
+		else:
+			dir = generic_path.Path(aDir)
+
+		sysDef = dir.Append(self.systemDefinition)
+		if not sysDef.isFile():
+			return None
+
+		return sysDef
+
+
+	def FindComponentIn(self, aDir = None):
+		# look for a bld.inf
+
+		if aDir is None:
+			dir = generic_path.CurrentDir()
+		else:
+			dir = generic_path.Path(aDir)
+
+		bldInf = dir.Append(self.buildInformation)
+
+		if bldInf.isFile():
+			return bldInf
+
+		return None
+
+	def GenerateGenericSpecs(self, configsToBuild):
+		# if a Configuration has any config-wide interfaces
+		# then add a Specification node to call each of them.
+		configWide = {}
+		genericSpecs = []
+		for c in configsToBuild:
+			evaluator = self.GetEvaluator(None, c)
+			iface = evaluator.Get("INTERFACE.config")
+			if iface:
+				if iface in configWide:
+					# seen it already, so reuse the node
+					filter = configWide[iface]
+					filter.AddConfigCondition(c.name)
+				else:
+					# create a new node
+					filter = raptor_data.Filter(name = "config_wide")
+					filter.AddConfigCondition(c.name)
+					for i in iface.split():
+						spec = raptor_data.Specification(i)
+						spec.SetInterface(i)
+						filter.AddChildSpecification(spec)
+					# remember it, use it
+					configWide[iface] = filter
+					genericSpecs.append(filter)
+
+		return genericSpecs
+
+
+	def GetEvaluator(self, specification, configuration, gathertools=False):
+		""" this will perform some caching later """
+		return raptor_data.Evaluator(specification, configuration, gathertools=gathertools, cache = self.cache)
+
+
+	def Make(self, makefileset):
+		if not self.noBuild and makefileset is not None:
+			if self.maker.Make(makefileset):
+				self.Info("The make-engine exited successfully.")
+				return True
+			else:
+				self.Error("The make-engine exited with errors.")
+				return False
+		else:
+			self.Info("No build performed")
+
+
+
+	def Report(self):
+		if self.quiet:
+			return
+
+		self.endtime = time.time()
+		self.runtime = int(0.5 + self.endtime - self.starttime)
+		self.raptor_params.runtime = self.runtime
+		self.Info("Run time %s seconds" % self.runtime)
+
+	def AssertBuildOK(self):
+		"""Raise a BuildCannotProgressException if no further processing is required
+		"""
+		if self.Skip():
+			raise BuildCannotProgressException("")
+
+		return True
+
+	def Skip(self):
+		"""Indicate not to perform operation if:
+		   fatalErrorState is set
+		   an error code is set but we're not in keepgoing mode
+		"""
+		return self.fatalErrorState or ((self.errorCode != 0) and (not self.keepGoing))
+
+
+	# log file open/close
+
+	def OpenLog(self):
+		"""Open a log file for the various I/O methods to write to."""
+
+		try:
+			# Find all the raptor plugins and put them into a pluginbox.
+			if not self.systemPlugins.isAbsolute():
+				self.systemPlugins = self.home.Append(self.systemPlugins)
+
+			self.pbox = pluginbox.PluginBox(str(self.systemPlugins))
+
+			self.raptor_params = BuildStats(self)
+
+			# Open the requested plugins using the pluginbox
+			self.out.open(self.raptor_params, self.filterList, self.pbox)
+
+			# log header
+			self.out.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n")
+
+			namespace = "http://symbian.com/xml/build/log"
+			progress_namespace = "http://symbian.com/xml/build/log/progress"
+			schema = "http://symbian.com/xml/build/log/1_0.xsd"
+
+			self.out.write("<buildlog sbs_version=\"%s\" xmlns=\"%s\" xmlns:progress=\"%s\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"%s %s\">\n"
+						   % (raptor_version.fullversion(), namespace, progress_namespace, namespace, schema))
+			self.logOpen = True
+		except Exception,e:
+			self.out = sys.stdout # make sure that we can actually get errors out.
+			self.logOpen = False
+			self.FatalError("Unable to open the output logs: %s" % str(e))
+
+	def CloseLog(self):
+		if self.logOpen:
+			self.out.summary()
+			self.out.write("</buildlog>\n")
+
+			if not self.out.close():
+				self.errorCode = 1
+
+
+	def Cleanup(self):
+		# ensure that the toolset cache is flushed.
+		if self.toolset is not None:
+			self.toolset.write()
+
+	# I/O methods
+
+	@staticmethod
+	def attributeString(dictionary):
+		"turn a dictionary into a string of XML attributes"
+		atts = ""
+		for a,v in dictionary.items():
+			atts += " " + a + "='" + v + "'"
+		return atts
+
+	def Info(self, format, *extras, **attributes):
+		"""Send an information message to the configured channel
+				(XML control characters will be escaped)
+		"""
+		self.out.write("<info" + self.attributeString(attributes) + ">" +
+		               escape(format % extras) + "</info>\n")
+
+	def InfoDiscovery(self, object_type, count):
+		if self.timing:
+			try:
+				self.out.write(raptor_timing.Timing.discovery_string(object_type = object_type,
+						count = count))
+			except Exception, exception:
+				self.Error(exception.Text, function = "InfoDiscoveryTime")
+
+	def InfoStartTime(self, object_type, task, key):
+		if self.timing:
+			try:
+				self.out.write(raptor_timing.Timing.start_string(object_type = object_type,
+						task = task, key = key))
+			except Exception, exception:
+				self.Error(exception.Text, function = "InfoStartTime")
+
+	def InfoEndTime(self, object_type, task, key):
+		if self.timing:
+			try:
+				self.out.write(raptor_timing.Timing.end_string(object_type = object_type,
+						task = task, key = key))
+			except Exception, exception:
+				self.Error(exception.Text, function = "InfoEndTime")
+
+	def Debug(self, format, *extras, **attributes):
+		"Send a debugging message to the configured channel"
+
+		# the debug text is out of our control so wrap it in a CDATA
+		# in case it contains characters special to XML... like <>
+		if self.debugOutput:
+			self.out.write("<debug" + self.attributeString(attributes) + ">" +
+			               "><![CDATA[\n" + (format % extras) + "\n]]></debug>\n")
+
+	def Warn(self, format, *extras, **attributes):
+		"""Send a warning message to the configured channel
+				(XML control characters will be escaped)
+		"""
+		self.out.write("<warning" + self.attributeString(attributes) + ">" +
+		               escape(format % extras) + "</warning>\n")
+
+	def FatalError(self, format, *extras, **attributes):
+		"""Send an error message to the configured channel. This implies such a serious
+		   error that the entire build must be shut down asap whilst still finishing off
+		   correctly whatever housekeeping is possible e.g. producing error reports.
+		   Remains quiet if the raptor object is already in a fatal state since there
+		   further errors are probably triggered by the first.
+		"""
+		if not self.fatalErrorState:
+			self.out.write("<error" + self.attributeString(attributes) + ">" +
+			               (format % extras) + "</error>\n")
+			self.errorCode = 1
+			self.fatalErrorState = True
+
+	def Error(self, format, *extras, **attributes):
+		"""Send an error message to the configured channel
+				(XML control characters will be escaped)
+		"""
+		self.out.write("<error" + self.attributeString(attributes) + ">" +
+		               escape(format % extras) + "</error>\n")
+		self.errorCode = 1
+
+
+	def PrintXML(self, format, *extras):
+		"Print to configured channel (no newline is added) (assumes valid xml)"
+		if format:
+			self.out.write(format % extras)
+
+	def GetLayersFromCLI(self):
+		"""Returns the list of layers as specified by the
+		   commandline interface to Raptor e.g. parameters
+		   or the current directory"""
+		layers=[]
+		# Look for bld.infs or sysdefs in the current dir if none were specified
+		if self.systemDefinitionFile == None and len(self.commandlineComponents) == 0:
+			if not self.preferBuildInfoToSystemDefinition:
+				cwd = os.getcwd()
+				self.systemDefinitionFile = self.FindSysDefIn(cwd)
+				if self.systemDefinitionFile == None:
+					aComponent = self.FindComponentIn(cwd)
+					if aComponent:
+						layers.append(Layer('default',[aComponent]))
+			else:
+				aComponent = self.FindComponentIn(cwd)
+				if aComponent is None:
+					self.systemDefinitionFile = self.FindSysDefIn(cwd)
+				else:
+					layers.append(Layer('default',[aComponent]))
+
+			if len(layers) <= 0 and  self.systemDefinitionFile == None:
+				self.Warn("No default bld.inf or system definition file found in current directory (%s)", cwd)
+
+		# If we now have a System Definition to parse then get the layers of components
+		if self.systemDefinitionFile != None:
+			systemModel = raptor_xml.SystemModel(self, self.systemDefinitionFile, self.systemDefinitionBase)
+			layers = self.GatherSysModelLayers(systemModel, self.systemDefinitionRequestedLayers)
+
+		# Now get components specified on a commandline - build them after any
+		# layers in the system definition.
+		if len(self.commandlineComponents) > 0:
+			layers.append(Layer('commandline',self.commandlineComponents))
+
+		# If we aren't building components in order then flatten down
+		# the groups
+		if not self.systemDefinitionOrderLayers:
+			# Flatten the layers into one group of components if
+			# we are not required to build them in order.
+			newcg = Layer("all")
+			for cg in layers:
+				for c in cg:
+					newcg.add(c)
+			layers = [newcg]
+
+		return layers
+
+	def Query(self):
+		"process command-line queries."
+		
+		if self.mission != Raptor.M_QUERY:
+			return 0
+		
+		# establish an object cache based on the current settings
+		self.LoadCache()
+			
+		# our "self" is a valid object for initialising an API Context
+		import raptor_api
+		api = raptor_api.Context(self)
+		
+		print "<sbs version='%s'>" % raptor_version.numericversion()
+		
+		for q in self.queries:
+			try:
+				print api.stringquery(q)
+				
+			except Exception, e:
+				self.Error("exception '%s' with query '%s'", str(e), q)
+		
+		print "</sbs>"	
+		return self.errorCode
+	
+	def Build(self):
+
+		if self.mission != Raptor.M_BUILD: # help or version requested instead.
+			return 0
+
+		# open the log file
+		self.OpenLog()
+
+
+		try:
+			# show the command and platform info
+			self.AssertBuildOK()
+			self.Introduction()
+			# establish an object cache
+			self.AssertBuildOK()
+
+			self.LoadCache()
+
+			# find out what configurations to build
+			self.AssertBuildOK()
+			buildUnitsToBuild = self.GetBuildUnitsToBuild(self.configNames)
+
+			if len(buildUnitsToBuild) == 0:
+				raise BuildCannotProgressException("No configurations to build.")
+			
+			self.buildUnitsToBuild = buildUnitsToBuild
+
+			# find out what components to build, and in what way
+			layers = []
+
+			self.AssertBuildOK()
+			if len(buildUnitsToBuild) >= 0:
+				layers = self.GetLayersFromCLI()
+
+			componentCount = reduce(lambda x,y : x + y, [len(cg) for cg in layers])
+
+			if not componentCount > 0:
+				raise BuildCannotProgressException("No components to build.")
+
+			# check the configurations (tools versions)
+			self.AssertBuildOK()
+
+			if self.toolcheck != 'off':
+				self.CheckConfigs(buildUnitsToBuild)
+			else:
+				self.Info("Not Checking Tool Versions")
+
+			self.AssertBuildOK()
+
+			# Setup a make engine.
+			if not self.maker:
+				try:
+					self.maker = raptor_make.MakeEngine(self, self.makeEngine)
+				except raptor_make.BadMakeEngineException,e:
+					self.Error("Unable to use make engine: %s " % str(e))
+					
+
+			self.AssertBuildOK()
+
+			# if self.doParallelParsing and not (len(layers) == 1 and len(layers[0]) == 1):
+			if self.doParallelParsing:
+				# Create a Makefile to parse components in parallel and build them
+				for l in layers:
+					l.meta_realise(self)
+			else:
+				# Parse components serially, creating one set of makefiles
+				# create non-component specs
+				self.generic_specs = self.GenerateGenericSpecs(buildUnitsToBuild)
+
+				self.AssertBuildOK()
+				for l in layers:
+					# create specs for a specific group of components
+					l.realise(self)
+
+		except BuildCannotProgressException,b:
+			if str(b) != "":
+				self.Info(str(b))
+
+		# final report
+		if not self.fatalErrorState:
+			self.Report()
+
+		self.Cleanup()
+
+		# close the log file
+		self.CloseLog()
+
+		return self.errorCode
+
+	@classmethod
+	def CreateCommandlineBuild(cls, argv):
+		""" Perform a 'typical' build. """
+		# configure the framework
+
+		build = Raptor()
+		build.AssertBuildOK()
+		build.ConfigFile()
+		build.ProcessConfig()
+		build.CommandLine(argv)
+
+		return build
+
+
+
+# Class for passing constricted parameters to filters
+class BuildStats(object):
+
+	def __init__(self, raptor_instance):
+		self.incoming_epocroot = incoming_epocroot
+		self.epocroot = epocroot
+		self.logFileName = raptor_instance.logFileName
+		self.quiet = raptor_instance.quiet
+		self.doCheck = raptor_instance.doCheck
+		self.doWhat = raptor_instance.doWhat
+		self.platform = hostplatform
+		self.skipAll = raptor_instance.fatalErrorState
+		self.timestring = raptor_instance.timestring
+		self.targets = raptor_instance.targets
+		self.runtime = 0
+		self.name = name
+
+
+# raptor module functions
+
+def Main(argv):
+	"""The main entry point for Raptor.
+
+	argv is a list of command-line parameters,
+	NOT including the name of the calling script.
+
+	The return value is zero for success and non-zero for failure."""
+
+	DisplayBanner()
+
+	# object which represents a build
+	b = Raptor.CreateCommandlineBuild(argv)
+
+	if b.mission == Raptor.M_QUERY:
+		return b.Query()
+	
+	return b.Build()
+
+
+def DisplayBanner():
+	"""Stuff that needs printing out for every command."""
+	pass
+
+
+
+
+# end of the raptor module
--- a/sbsv2/raptor/python/raptor_cache.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/raptor_cache.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,223 +1,219 @@
-#
-# 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: 
-# raptor_cache module
-# This module represents a cache of objects for a Raptor program.
-#
-
-import raptor_data
-import raptor_xml
-import generic_path
-import os
-
-# raptor_cache module attributes
-
-
-# raptor_cache module classes
-
-class Cache:
-
-	def __init__(self, Raptor):
-		self.raptor = Raptor
-		self.aliases = {}
-		self.groups = {}
-		self.interfaces = {}
-		self.variants = {}
-
-	def Load(self, gPathOrGPathList, cacheID = ""):
-		"""scan directory for xml files containing Raptor objects.
-		Input is either a generic path object or a list of
-		generic path objects.
-
-		If a cacheID is supplied then the loaded objects are
-		placed into containers which are marked with that ID.
-		This is useful for Interfaces which may be loaded from
-		several locations (different epoc32 trees for example)
-		but need to be kept separate.
-		"""
-
-		pathlist = []
-		filenames = []
-
-		# Create pathlist - this will be of length one if gPathOrGPathList is a
-		# generic path object; otherwise it's a list so just make all supplied paths generic
-		if isinstance(gPathOrGPathList, list):
-			pathlist = map(lambda x: x.GetLocalString(), gPathOrGPathList)
-		elif isinstance(gPathOrGPathList, generic_path.Path):
-			pathlist = [gPathOrGPathList.GetLocalString()]
-		else:
-			self.raptor.Warn("Empty list or blank path supplied.")
-
-		# Only when debugging, print the list. The for loop will be
-		# skipped if not in debug mode
-		if self.raptor.debugOutput:
-			for path in pathlist:
-				self.raptor.Debug("Loading XML cache from %s", path)
-
-		# Internal function to get the list of XML
-		# files recursively
-		def getXmlFiles(aDir, aFileList):
-			dirList = []
-			for fname in os.listdir(aDir):
-				path = os.path.join(aDir, fname)
-				if os.path.isdir(path):
-					dirList.append(path)
-				else: # It's a file
-					if path.endswith(".xml"): # Only files ending in .xml get added
-						aFileList.append(path)
-			# Now iterate over directory list; this way, the files in the top level of
-			# aDir will be added before all files in any subdirectory of aDir
-			for dir in dirList:
-				getXmlFiles(dir, aFileList)
-
-		# This will add all files in all top level directories and all XML files
-		for path in pathlist:
-			# gPathOrGPathList passed to Load() can be a file or a
-			# directory, or a list of files or directories or both
-			if os.path.isfile(path):
-				if path.endswith(".xml"): # Only files whose names end in .xml get added
-					filenames.append(path)
-			elif os.path.isdir(path):
-				getXmlFiles(path, filenames)
-			else: # it isn't a file or directory
-				self.raptor.Warn("No file or directory found for '%s'", path)
-
-		if not filenames:
-			# No XML files found in any of the paths
-			return
-
-		# Parse XML files, and add the objects to our
-		# configuration/interface/variant dictionaries
-		for fullpath in filenames:
-			try:
-				objects = raptor_xml.Read(self.raptor, fullpath)
-
-			except raptor_xml.XMLError:
-				self.raptor.Warn("Failed to read XML file %s", fullpath)
-				continue
-
-			self.raptor.Debug("%d objects found in XML file %s", len(objects), fullpath)
-
-			for obj in objects:
-				# top-level objects need to know which XML file they came from.
-				obj.SetSourceFile(fullpath)
-				try:
-					self.AddObject(obj, cacheID)
-				except UnexpectedObjectError:
-					self.raptor.Warn("Unexpected object %s", str(obj))
-
-	def AddObject(self, obj, cacheID):
-		"""add a Group, Alias, Interface or Variant.
-
-		The cacheID is only used to separate Interfaces.
-		"""
-
-		if isinstance(obj, raptor_data.Group):
-			self.AddGroup(obj)
-		elif isinstance(obj, raptor_data.Alias):
-			self.AddAlias(obj)
-		elif isinstance(obj, raptor_data.Interface):
-			self.AddInterface(obj, cacheID)
-		elif isinstance(obj, raptor_data.Variant):
-			self.AddVariant(obj)
-		else:
-			raise UnexpectedObjectError
-
-
-	def FindNamedGroup(self, name):
-		return self.groups[name]
-
-	def AddGroup(self, obj):
-		if obj.name in self.groups:
-			self.WarnDuplicate("group", self.groups[obj.name], obj)
-			return
-
-		obj.SetOwner(self.raptor)
-		self.groups[obj.name] = obj
-
-	def FindNamedAlias(self, name):
-		return self.aliases[name]
-
-	def AddAlias(self, obj):
-		if obj.name in self.aliases:
-			self.WarnDuplicate("alias", self.aliases[obj.name], obj)
-			return
-
-		obj.SetOwner(self.raptor)
-		self.aliases[obj.name] = obj
-
-
-	def FindNamedInterface(self, name, cacheID = ""):
-		try:
-			return self.interfaces[cacheID][name]
-		except KeyError, e:
-			if cacheID == "":
-				raise e
-			else:
-				return self.interfaces[""][name]
-
-
-	def AddInterface(self, obj, cacheID):
-		if not cacheID in self.interfaces:
-			self.interfaces[cacheID] = {}
-
-		if obj.name in self.interfaces[cacheID]:
-			self.WarnDuplicate("interface", self.interfaces[cacheID][obj.name], obj)
-			return
-
-		obj.SetOwner(self.raptor)
-		obj.cacheID = cacheID
-		self.interfaces[cacheID][obj.name] = obj
-
-
-	def FindNamedVariant(self, name):
-		return self.variants[name]
-
-
-	def AddVariant(self, obj):
-		# anonymous variants can never be referenced, so ignore them
-		if obj.name:
-			if self.variants.has_key(obj.name):
-				self.WarnDuplicate("variant", self.variants[obj.name], obj)
-				return
-
-			obj.SetOwner(self.raptor)
-			self.variants[obj.name] = obj
-
-
-	def WarnDuplicate(self, type, objOld, objNew):
-		"""tell us where duplicate objects came from."""
-		oldSource = objOld.source
-		if oldSource == None:
-			oldSource = "unknown"
-
-		newSource = objNew.source
-		if newSource == None:
-			newSource = "unknown"
-
-		# don't warn if we are reloading the object from the same
-		# file as before: since that is quite ligitimate.
-		if oldSource == newSource and oldSource != "unknown":
-			return
-
-		# actually this is just for information not a warning
-		self.raptor.Info("Duplicate %s '%s' (the one from '%s' will override the one in '%s')",
-						 type, objOld.name, oldSource, newSource)
-
-
-class UnexpectedObjectError(Exception):
-	pass
-
-
-# end of the raptor_cache module
+#
+# 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: 
+# raptor_cache module
+# This module represents a cache of objects for a Raptor program.
+#
+
+import raptor_data
+import raptor_xml
+import generic_path
+import os
+
+# raptor_cache module attributes
+
+
+# raptor_cache module classes
+
+class Cache:
+
+	def __init__(self, Raptor):
+		self.raptor = Raptor
+		self.aliases = {}
+		self.groups = {}
+		self.interfaces = {}
+		self.variants = {}
+
+	def Load(self, gPathOrGPathList, cacheID = ""):
+		"""scan directory for xml files containing Raptor objects.
+		Input is either a generic path object or a list of
+		generic path objects.
+
+		If a cacheID is supplied then the loaded objects are
+		placed into containers which are marked with that ID.
+		This is useful for Interfaces which may be loaded from
+		several locations (different epoc32 trees for example)
+		but need to be kept separate.
+		"""
+
+		pathlist = []
+		filenames = []
+
+		# Create pathlist - this will be of length one if gPathOrGPathList is a
+		# generic path object; otherwise it's a list so just make all supplied paths generic
+		if isinstance(gPathOrGPathList, list):
+			pathlist = map(lambda x: x.GetLocalString(), gPathOrGPathList)
+		elif isinstance(gPathOrGPathList, generic_path.Path):
+			pathlist = [gPathOrGPathList.GetLocalString()]
+		else:
+			self.raptor.Warn("Empty list or blank path supplied.")
+
+		# Only when debugging, print the list. The for loop will be
+		# skipped if not in debug mode
+		if self.raptor.debugOutput:
+			for path in pathlist:
+				self.raptor.Debug("Loading XML cache from %s", path)
+
+		# Internal function to get the list of XML
+		# files recursively
+		def getXmlFiles(aDir, aFileList):
+			dirList = []
+			for fname in os.listdir(aDir):
+				path = os.path.join(aDir, fname)
+				if os.path.isdir(path):
+					dirList.append(path)
+				else: # It's a file
+					if path.endswith(".xml"): # Only files ending in .xml get added
+						aFileList.append(path)
+			# Now iterate over directory list; this way, the files in the top level of
+			# aDir will be added before all files in any subdirectory of aDir
+			for dir in dirList:
+				getXmlFiles(dir, aFileList)
+
+		# This will add all files in all top level directories and all XML files
+		for path in pathlist:
+			# gPathOrGPathList passed to Load() can be a file or a
+			# directory, or a list of files or directories or both
+			if os.path.isfile(path):
+				if path.endswith(".xml"): # Only files whose names end in .xml get added
+					filenames.append(path)
+			elif os.path.isdir(path):
+				getXmlFiles(path, filenames)
+			else: # it isn't a file or directory
+				self.raptor.Warn("No file or directory found for '%s'", path)
+
+		if not filenames:
+			# No XML files found in any of the paths
+			return
+
+		# Parse XML files, and add the objects to our
+		# configuration/interface/variant dictionaries
+		for fullpath in filenames:
+			try:
+				objects = raptor_xml.Read(self.raptor, fullpath)
+
+			except raptor_xml.XMLError:
+				self.raptor.Warn("Failed to read XML file %s", fullpath)
+				continue
+
+			self.raptor.Debug("%d objects found in XML file %s", len(objects), fullpath)
+
+			for obj in objects:
+				# top-level objects need to know which XML file they came from.
+				obj.SetSourceFile(fullpath)
+				try:
+					self.AddObject(obj, cacheID)
+				except UnexpectedObjectError:
+					self.raptor.Warn("Unexpected object %s", str(obj))
+
+	def AddObject(self, obj, cacheID):
+		"""add a Group, Alias, Interface or Variant.
+
+		The cacheID is only used to separate Interfaces.
+		"""
+
+		if isinstance(obj, raptor_data.Group):
+			self.AddGroup(obj)
+		elif isinstance(obj, raptor_data.Alias):
+			self.AddAlias(obj)
+		elif isinstance(obj, raptor_data.Interface):
+			self.AddInterface(obj, cacheID)
+		elif isinstance(obj, raptor_data.Variant):
+			self.AddVariant(obj)
+		else:
+			raise UnexpectedObjectError
+
+
+	def FindNamedGroup(self, name):
+		return self.groups[name]
+
+	def AddGroup(self, obj):
+		if obj.name in self.groups:
+			self.WarnDuplicate("group", self.groups[obj.name], obj)
+			return
+
+		self.groups[obj.name] = obj
+
+	def FindNamedAlias(self, name):
+		return self.aliases[name]
+
+	def AddAlias(self, obj):
+		if obj.name in self.aliases:
+			self.WarnDuplicate("alias", self.aliases[obj.name], obj)
+			return
+
+		self.aliases[obj.name] = obj
+
+
+	def FindNamedInterface(self, name, cacheID = ""):
+		try:
+			return self.interfaces[cacheID][name]
+		except KeyError, e:
+			if cacheID == "":
+				raise e
+			else:
+				return self.interfaces[""][name]
+
+
+	def AddInterface(self, obj, cacheID):
+		if not cacheID in self.interfaces:
+			self.interfaces[cacheID] = {}
+
+		if obj.name in self.interfaces[cacheID]:
+			self.WarnDuplicate("interface", self.interfaces[cacheID][obj.name], obj)
+			return
+
+		obj.cacheID = cacheID
+		self.interfaces[cacheID][obj.name] = obj
+
+
+	def FindNamedVariant(self, name):
+		return self.variants[name]
+
+
+	def AddVariant(self, obj):
+		# anonymous variants can never be referenced, so ignore them
+		if obj.name:
+			if self.variants.has_key(obj.name):
+				self.WarnDuplicate("variant", self.variants[obj.name], obj)
+				return
+
+			self.variants[obj.name] = obj
+
+
+	def WarnDuplicate(self, type, objOld, objNew):
+		"""tell us where duplicate objects came from."""
+		oldSource = objOld.source
+		if oldSource == None:
+			oldSource = "unknown"
+
+		newSource = objNew.source
+		if newSource == None:
+			newSource = "unknown"
+
+		# don't warn if we are reloading the object from the same
+		# file as before: since that is quite ligitimate.
+		if oldSource == newSource and oldSource != "unknown":
+			return
+
+		# actually this is just for information not a warning
+		self.raptor.Info("Duplicate %s '%s' (the one from '%s' will override the one in '%s')",
+						 type, objOld.name, oldSource, newSource)
+
+
+class UnexpectedObjectError(Exception):
+	pass
+
+
+# end of the raptor_cache module
--- a/sbsv2/raptor/python/raptor_cli.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/raptor_cli.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,320 +1,336 @@
-#
-# 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: 
-# raptor_cli module
-# This module represents a Command Line Interpreter (CLI) for Raptor.
-# The interface with Raptor is the GetArgs() function, which is called
-# by a raptor.Raptor object.
-#
-
-import re
-import types
-import raptor
-import os
-import sys
-import tempfile
-from raptor_utilities import getOSPlatform
-
-from optparse import OptionParser # for parsing command line parameters
-
-fullCommandOption = "--command"
-miniCommandOption = "--co"  # update this if another "co" option is added
-
-# raptor_cli module attributes
-
-parser = OptionParser(prog = raptor.name,
-					  usage = """%prog [--help] [options] [variable=value] [target] ...
-
-Targets:
-
-BITMAP         Create bitmap files
-CLEAN          Remove built files and intermediates, but not exported files
-CLEANEXPORT    Remove exported files
-EXPORT         Copy exported files to destinations
-FINAL          Allow extension makefiles to execute final commands
-FREEZE         Freeze exported functions in a .DEF file
-LIBRARY        Create import libraries from frozen .DEF files
-LISTING        Create assembler listing files for source files
-REALLYCLEAN    Same as CLEAN but also remove exported files
-RESOURCE       Create resource files and AIFs
-ROMFILE        Create an IBY file to be included in a ROM
-TARGET         Create main executables
-WHAT           List all releaseable targets
-
-Examples:
-
-sbs -b my/group/bld.inf -c armv5        # build my component for target ARMV5
-sbs -b my/group/bld.inf -c armv5.test   # build my tests for target ARMV5
-
-sbs -c winscw CLEAN                     # clean emulator files
-sbs REALLYCLEAN                         # delete everything""")
-
-parser.add_option("-a","--sysdefbase",action="store",dest="sys_def_base",
-				help="Root directory for relative paths in the System Definition XML file.")
-
-parser.add_option("-b","--bldinf",action="append",dest="bld_inf_file",
-				help="Build information filename. Multiple -b options can be given.")
-
-parser.add_option("-c","--config",action="append",dest="config_name",
-				help="Configuration name to build. Multiple -c options can be given. The standard configs are all, armv5, armv7, default, tools, tools2 and winscw.")
-
-parser.add_option("--configpath", action="append",dest="config_list",
-				help="Append a list of paths to the default list of XML configuration folders. Use ';' as the separator on Windows, and ':' on Linux. Multiple --configpath options can be given.")
-
-parser.add_option("--check",action="store_true",dest="check",
-				help="Test for the existence of files created by the build, printing the ones which are missing. Do not build anything.")
-
-parser.add_option("--command",action="append",dest="command_file",
-				help="Provide a set of command-line options in a file.")
-
-parser.add_option("-d","--debug",action="store_true",dest="debugoutput",
-				help="Display information useful for debugging.")
-
-parser.add_option("-e","--engine",action="store",dest="make_engine",
-				help="Name of the make engine which runs the build.")
-
-parser.add_option("--export-only",action="store_true",dest="doExportOnly",
-				help="Generate exports only and do not create any make files.")
-
-parser.add_option("-f","--logfile",action="store",dest="logfile",
-				help="Name of the log file, or '-' for stdout.")
-
-parser.add_option("--filters",action="store",dest="filter_list",
-				help="Comma-separated list of names of the filters to use (case sensitive).")
-
-parser.add_option("-i","--ignore-os-detection",action="store_true",dest="ignore_os_detection",
-				help="Disables automatic application of OS variant based upon the OS version detected from each epoc32 tree.")
-
-parser.add_option("-j","--jobs",action="store",dest="number_of_jobs",
-                help="The maximum number of jobs that make should try and run in parallel (on a single machine).")
-
-parser.add_option("-k","--keepgoing",action="store_true",dest="keepgoing",
-				help="Continue building, even if some build commands fail.")
-
-parser.add_option("-l","--layer",action="append",dest="sys_def_layer",
-                help="Build a specific layer in the System Definition XML File. Multiple -l options can be given.")
-
-parser.add_option("-m","--makefile",action="store",dest="makefile",
-				help="Top-level makefile to be created.")
-
-parser.add_option("--mo",action="append",dest="make_option",
-				help="Option that must be passed through to the make engine. Multiple --mo options can be given.")
-
-parser.add_option("-n","--nobuild",action="store_true",dest="nobuild",
-				help="Just create makefiles, do not build anything.")
-
-parser.add_option("--no-depend-include",action="store_true",dest="noDependInclude",
-				help="Do not include generated dependency files. This is only useful for extremely large non-incremental builds.")
-				
-parser.add_option("-o","--orderlayers",action="store_true",dest="sys_def_order_layers",
-				help="Build layers in the System Definition XML file in the order listed or, if given, in the order of -l options.")
-
-parser.add_option("-p","--project",action="append",dest="project_name",
-                help="Build a specific project (mmp or extension) in the given bld.inf file. Multiple -p options can be given.")
-
-parser.add_option("-q","--quiet",action="store_true",dest="quiet",
-				help="Run quietly, not generating output messages.")
-
-parser.add_option("-s","--sysdef",action="store",dest="sys_def_file",
-				help="System Definition XML filename.")
-
-parser.add_option("--source-target",action="append",dest="source_target",
-				help="Build the listed source or resource file in isolation - do not perform any dependent processing. Multiple --source-target options can be given.")
-
-parser.add_option("-t","--tries",action="store",dest="tries",
-				help="How many times to run a command before recording an error. The default is 1. This is useful for builds where transient failures can occur.")
-
-parser.add_option("--toolcheck",action="store",dest="toolcheck",
-			help= \
-				"""Possible values are:
-				  "on"     -  Check the versions of tools that will be used in the build. Use cached results from previous builds to save time. This is the default.
-
-  				  "off"    -  Do not check tool versions whatsoever.
-
-				  "forced" -  Check all tool versions. Don't use cached results.
-			""")
-parser.add_option("--pp",action="store",dest="parallel_parsing",
-				help="""Controls how metadata (e.g. bld.infs) are parsed in Parallel.
-					Possible values are:
-					"on"  - Parse bld.infs in parallel (should be faster on clusters/multicore machines)
-					"off" - Parse bld.infs serially 
-				     """)
-
-parser.add_option("-v","--version",action="store_true",dest="version",
-				help="Print the version number and exit.")
-
-parser.add_option("--what",action="store_true",dest="what",
-				help="Print out the names of the files created by the build. Do not build anything.")
-
-def GetArgs(Raptor, args):
-	"Process command line arguments for a Raptor object"
-	return DoRaptor(Raptor,args)
-
-def ReadCommandFile(filename, used):
-	if filename in used:
-		raise IOError("command file '%s' refers to itself" % filename)
-
-	args = []
-	try:
-		file = open(filename, "r")
-		for line in file.readlines():
-			args.extend(line.split())
-		file.close()
-	except:
-		raise IOError("couldn't read command file '%s'" % filename)
-
-	# expand any command files in the options we just read.
-	# making sure we don't get stuck in a loop.
-	usedPlusThis = used[:]
-	usedPlusThis.append(filename)
-	return ExpandCommandOptions(args, usedPlusThis)
-
-def ExpandCommandOptions(args, files = []):
-	"""recursively expand --command options."""
-	expanded = []
-	previousWasOpt = False
-
-	for a in args:
-		if previousWasOpt: # then this one is the filename
-			expanded.extend(ReadCommandFile(a, files))
-			previousWasOpt = False
-			continue
-
-		if a.startswith(miniCommandOption):
-			if "=" in a: # then this is opt=filename
-				opt = a.split("=")
-				if fullCommandOption.startswith(opt[0]):
-					expanded.extend(ReadCommandFile(opt[1], files))
-					continue
-			else: # the next one is the filename
-				if fullCommandOption.startswith(a):
-					previousWasOpt = True
-					continue
-
-		expanded.append(a) # an ordinary arg, nothing to do with command files
-
-	return expanded
-
-def DoRaptor(Raptor, args):
-	"Process raptor arguments"
-	#
-	# This should parse the args list and call methods on
-	# the Raptor object to store the appropriate data.
-
-	# Expand --command=file options, replacing them with the contents of the
-	# command file.
-
-	non_ascii_error = "Non-ASCII character in argument or command file"
-
-	try:
-		expanded_args = ExpandCommandOptions(args)
-		for arg in expanded_args:
-			for c in arg:
-				if ord(c) > 127:
-					Raptor.Error(non_ascii_error)
-					return False
-	except IOError, e:
-		Raptor.Error(str(e))
-		return False
-	except UnicodeDecodeError:
-		Raptor.Error(non_ascii_error)
-		return False
-
-	# parse the full set of arguments
-	(options, leftover_args) = parser.parse_args(expanded_args)
-
-	# the leftover_args are either variable assignments of the form a=b
-	# or target names.
-	regex = re.compile("^(.+)=(.*)$")
-	for leftover in leftover_args:
-		assignment = regex.findall(leftover)
-		if len(assignment) > 0:
-			Raptor.SetEnv(assignment[0][0],assignment[0][1])
-		else:
-			Raptor.AddTarget(leftover)
-
-	# Define the dictionary of functions to be used.
-	# Attributes and function names can be added easily.
-	# The calling attribute should be the same
-	# as specified when creating the add_option
-	functions = {'config_name': Raptor.AddConfigName,
-				 'config_list':Raptor.AddConfigList,
-				 'sys_def_file' : Raptor.SetSysDefFile,
-				 'sys_def_base' : Raptor.SetSysDefBase,
-				 'sys_def_layer' : Raptor.AddSysDefLayer,
-				 'sys_def_order_layers' : Raptor.SetSysDefOrderLayers,
-				 'bld_inf_file' : Raptor.AddBuildInfoFile,
-				 'logfile' : Raptor.SetLogFileName,
-				 'makefile' : Raptor.SetTopMakefile,
-				 'quiet' : Raptor.RunQuietly,
-				 'debugoutput' : Raptor.SetDebugOutput,
-				 'doExportOnly' : Raptor.SetExportOnly,
-				 'keepgoing': Raptor.SetKeepGoing,
-				 'nobuild' : Raptor.SetNoBuild,
-				 'make_engine': Raptor.SetMakeEngine,
-				 'make_option': Raptor.AddMakeOption,
-				 'noDependInclude': Raptor.SetNoDependInclude,
-				 'number_of_jobs': Raptor.SetJobs,
-				 'project_name' :  Raptor.AddProject,
-				 'filter_list' : Raptor.FilterList,
-				 'ignore_os_detection': Raptor.IgnoreOsDetection,
-				 'check' :  Raptor.SetCheck,
-				 'what' :  Raptor.SetWhat,
-				 'tries' : Raptor.SetTries,
-				 'toolcheck' : Raptor.SetToolCheck,
-				 'source_target' : Raptor.AddSourceTarget,
-				 'command_file' : CommandFile,
-				'parallel_parsing' : Raptor.SetParallelParsing,
-			 	'version' : Raptor.PrintVersion
-				}
-
-	# Check if Quiet mode has been specified (otherwise we will make noise)
-	if parser.values.quiet:
-		Raptor.RunQuietly(True)
-
-	# some options imply that Raptor should exit immediately (e.g. --version)
-	keepGoing = True
-
-	if parser.values.version:
-		keepGoing = False
-
-	# Parse through the command line arguments passed, and call the
-	# corresponding function with the correct parameter.
-	# Since options is a OptParse.Value instance, it can be iterated over.
-	# This implementation helps avoid lengthy if-else statements
-	for opt in options.__dict__.items():
-		call_function = functions[str(opt[0])]
-		values = opt[1]
-		if not values:
-			pass
-		else:
-			if type(values) == types.ListType: # Check if the argument type is a list or a string. If list, then iterate through it and call the functions
-				for val in values:
-					keepGoing = (call_function(val) and keepGoing)
-			else:
-					keepGoing = (call_function(values) and keepGoing)
-
-	return keepGoing
-
-def CommandFile(file):
-	"this should never be called because we expand --command in this module."
-	print raptor.name + ": error: command file '%s' was not expanded" % file
-	return False
-
-
-
-
-# end of the raptor_cli module
-
-
+#
+# 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: 
+# raptor_cli module
+# This module represents a Command Line Interpreter (CLI) for Raptor.
+# The interface with Raptor is the GetArgs() function, which is called
+# by a raptor.Raptor object.
+#
+
+import types
+import raptor
+
+from optparse import OptionParser # for parsing command line parameters
+
+fullCommandOption = "--command"
+miniCommandOption = "--co"  # update this if another "co" option is added
+
+# raptor_cli module attributes
+
+parser = OptionParser(prog = raptor.name,
+					  usage = """%prog [--help] [options] [target] ...
+
+Targets:
+
+BITMAP         Create bitmap files
+CLEAN          Remove built files and intermediates, but not exported files
+CLEANEXPORT    Remove exported files
+EXPORT         Copy exported files to destinations
+FINAL          Allow extension makefiles to execute final commands
+FREEZE         Freeze exported functions in a .DEF file
+LIBRARY        Create import libraries from frozen .DEF files
+LISTING        Create assembler listing files for source files
+REALLYCLEAN    Same as CLEAN but also remove exported files
+RESOURCE       Create resource files
+ROMFILE        Create an IBY file to be included in a ROM
+TARGET         Create main executables
+WHAT           List all releaseable targets
+
+Examples:
+
+sbs -b my/group/bld.inf -c armv5        # build my component for target ARMV5
+sbs -b my/group/bld.inf -c armv5.test   # build my tests for target ARMV5
+
+sbs -c winscw CLEAN                     # clean emulator files
+sbs REALLYCLEAN                         # delete everything""")
+
+parser.add_option("-a","--sysdefbase",action="store",dest="sys_def_base",
+				help="Root directory for relative paths in the System Definition XML file.")
+
+parser.add_option("-b","--bldinf",action="append",dest="bld_inf_file",
+				help="Build information filename. Multiple -b options can be given.")
+
+parser.add_option("-c","--config",action="append",dest="config_name",
+				help="Configuration name to build. Multiple -c options can be given. The standard configs are all, armv5, armv7, default, tools, tools2 and winscw.")
+
+parser.add_option("--configpath", action="append",dest="config_list",
+				help="Append a list of paths to the default list of XML configuration folders. Use ';' as the separator on Windows, and ':' on Linux. Multiple --configpath options can be given.")
+
+parser.add_option("--check",action="store_true",dest="check",
+				help="Test for the existence of files created by the build, printing the ones which are missing. Do not build anything.")
+
+parser.add_option("--command",action="append",dest="command_file",
+				help="Provide a set of command-line options in a file.")
+
+parser.add_option("-d","--debug",action="store_true",dest="debugoutput",
+				help="Display information useful for debugging.")
+
+parser.add_option("-e","--engine",action="store",dest="make_engine",
+				help="Name of the make engine which runs the build.")
+
+parser.add_option("--export-only",action="store_true",dest="doExportOnly",
+				help="Generate exports only and do not create any make files.")
+
+parser.add_option("--noexport",action="store_true",dest="doExport",
+				help="Don't export any files - useful in some builds when you know exports have already been done.")
+
+parser.add_option("-f","--logfile",action="store",dest="logfile",
+				help="Name of the log file, or '-' for stdout.")
+
+parser.add_option("--filters",action="store",dest="filter_list",
+				help="Comma-separated list of names of the filters to use (case sensitive).")
+
+parser.add_option("-i","--ignore-os-detection",action="store_true",dest="ignore_os_detection",
+				help="Disables automatic application of OS variant based upon the OS version detected from each epoc32 tree.")
+
+parser.add_option("-j","--jobs",action="store",dest="number_of_jobs",
+                help="The maximum number of jobs that make should try and run in parallel (on a single machine).")
+
+parser.add_option("-k","--keepgoing",action="store_true",dest="keepgoing",
+				help="Continue building, even if some build commands fail.")
+
+parser.add_option("-l","--layer",action="append",dest="sys_def_layer",
+                help="Build a specific layer in the System Definition XML File. Multiple -l options can be given.")
+
+parser.add_option("-m","--makefile",action="store",dest="makefile",
+				help="Top-level makefile to be created.")
+
+parser.add_option("--mo",action="append",dest="make_option",
+				help="Option that must be passed through to the make engine. Multiple --mo options can be given.")
+
+parser.add_option("-n","--nobuild",action="store_true",dest="nobuild",
+				help="Just create makefiles, do not build anything.")
+
+parser.add_option("--no-depend-include",action="store_true",dest="noDependInclude",
+				help="Do not include generated dependency files. This is only useful for extremely large non-incremental builds.")
+
+parser.add_option("--no-depend-generate",action="store_true",dest="noDependGenerate",
+				help="Do not generate dependency files. This is only useful for extremely large non-incremental builds.  Implies --no-depend-include.")
+				
+parser.add_option("-o","--orderlayers",action="store_true",dest="sys_def_order_layers",
+				help="Build layers in the System Definition XML file in the order listed or, if given, in the order of -l options.")
+
+parser.add_option("-p","--project",action="append",dest="project_name",
+                help="Build a specific project (mmp or extension) in the given bld.inf file. Multiple -p options can be given.")
+
+parser.add_option("-q","--quiet",action="store_true",dest="quiet",
+				help="Run quietly, not generating output messages.")
+
+parser.add_option("--query",action="append",dest="query",
+				help="""Access various build settings and options using a basic API. The current options are:
+				
+				* aliases - return all the values that can be sensibly used with the sbs -c option.
+				
+				* products - return all the values that can be "." appended to an alias to specialise it for a product build.
+				
+				* config[x] - return a set of values that represent the build configuration "x". Typically "x" will be an alias name or an alias followed by "." followed by a product.
+				
+				Multiple --query options can be given.
+				""")
+
+parser.add_option("-s","--sysdef",action="store",dest="sys_def_file",
+				help="System Definition XML filename.")
+
+parser.add_option("--source-target",action="append",dest="source_target",
+				help="Build the listed source or resource file in isolation - do not perform any dependent processing. Multiple --source-target options can be given.")
+
+parser.add_option("-t","--tries",action="store",dest="tries",
+				help="How many times to run a command before recording an error. The default is 1. This is useful for builds where transient failures can occur.")
+
+parser.add_option("--toolcheck",action="store",dest="toolcheck",
+			help= \
+				"""Possible values are:
+				  "on"     -  Check the versions of tools that will be used in the build. Use cached results from previous builds to save time. This is the default.
+
+  				  "off"    -  Do not check tool versions whatsoever.
+
+				  "forced" -  Check all tool versions. Don't use cached results.
+			""")
+
+parser.add_option("--timing",action="store_true",dest="timing",
+			help="Show extra timing information for various processes in the build.")
+
+parser.add_option("--pp",action="store",dest="parallel_parsing",
+				help="""Controls how metadata (e.g. bld.infs) are parsed in Parallel.
+					Possible values are:
+					"on"  - Parse bld.infs in parallel (should be faster on clusters/multicore machines)
+					"slave" - used internally by Raptor 
+					"off" - Parse bld.infs serially 
+				     """)
+
+parser.add_option("-v","--version",action="store_true",dest="version",
+				help="Print the version number and exit.")
+
+parser.add_option("--what",action="store_true",dest="what",
+				help="Print out the names of the files created by the build. Do not build anything.")
+
+def GetArgs(Raptor, args):
+	"Process command line arguments for a Raptor object"
+	return DoRaptor(Raptor,args)
+
+def ReadCommandFile(filename, used):
+	if filename in used:
+		raise IOError("command file '%s' refers to itself" % filename)
+
+	args = []
+	try:
+		file = open(filename, "r")
+		for line in file.readlines():
+			args.extend(line.split())
+		file.close()
+	except:
+		raise IOError("couldn't read command file '%s'" % filename)
+
+	# expand any command files in the options we just read.
+	# making sure we don't get stuck in a loop.
+	usedPlusThis = used[:]
+	usedPlusThis.append(filename)
+	return ExpandCommandOptions(args, usedPlusThis)
+
+def ExpandCommandOptions(args, files = []):
+	"""recursively expand --command options."""
+	expanded = []
+	previousWasOpt = False
+
+	for a in args:
+		if previousWasOpt: # then this one is the filename
+			expanded.extend(ReadCommandFile(a, files))
+			previousWasOpt = False
+			continue
+
+		if a.startswith(miniCommandOption):
+			if "=" in a: # then this is opt=filename
+				opt = a.split("=")
+				if fullCommandOption.startswith(opt[0]):
+					expanded.extend(ReadCommandFile(opt[1], files))
+					continue
+			else: # the next one is the filename
+				if fullCommandOption.startswith(a):
+					previousWasOpt = True
+					continue
+
+		expanded.append(a) # an ordinary arg, nothing to do with command files
+
+	return expanded
+
+def DoRaptor(Raptor, args):
+	"Process raptor arguments"
+	#
+	# This should parse the args list and call methods on
+	# the Raptor object to store the appropriate data.
+
+	# Expand --command=file options, replacing them with the contents of the
+	# command file.
+
+	non_ascii_error = "Non-ASCII character in argument or command file"
+
+	try:
+		expanded_args = ExpandCommandOptions(args)
+		for arg in expanded_args:
+			for c in arg:
+				if ord(c) > 127:
+					Raptor.Error(non_ascii_error)
+					return False
+	except IOError, e:
+		Raptor.Error(str(e))
+		return False
+	except UnicodeDecodeError:
+		Raptor.Error(non_ascii_error)
+		return False
+
+	# parse the full set of arguments
+	(options, leftover_args) = parser.parse_args(expanded_args)
+
+	# the leftover_args are target names.
+	for leftover in leftover_args:
+		Raptor.AddTarget(leftover)
+
+	# Define the dictionary of functions to be used.
+	# Attributes and function names can be added easily.
+	# The calling attribute should be the same
+	# as specified when creating the add_option
+	functions = {'config_name': Raptor.AddConfigName,
+				 'config_list':Raptor.AddConfigList,
+				 'sys_def_file' : Raptor.SetSysDefFile,
+				 'sys_def_base' : Raptor.SetSysDefBase,
+				 'sys_def_layer' : Raptor.AddSysDefLayer,
+				 'sys_def_order_layers' : Raptor.SetSysDefOrderLayers,
+				 'bld_inf_file' : Raptor.AddBuildInfoFile,
+				 'logfile' : Raptor.SetLogFileName,
+				 'makefile' : Raptor.SetTopMakefile,
+				 'quiet' : Raptor.RunQuietly,
+				 'debugoutput' : Raptor.SetDebugOutput,
+				 'doExportOnly' : Raptor.SetExportOnly,
+				 'doExport' : Raptor.SetNoExport,
+				 'keepgoing': Raptor.SetKeepGoing,
+				 'nobuild' : Raptor.SetNoBuild,
+				 'make_engine': Raptor.SetMakeEngine,
+				 'make_option': Raptor.AddMakeOption,
+				 'noDependInclude': Raptor.SetNoDependInclude,
+				 'noDependGenerate': Raptor.SetNoDependGenerate,
+				 'number_of_jobs': Raptor.SetJobs,
+				 'project_name' :  Raptor.AddProject,
+				 'query' : Raptor.AddQuery,
+				 'filter_list' : Raptor.FilterList,
+				 'ignore_os_detection': Raptor.IgnoreOsDetection,
+				 'check' :  Raptor.SetCheck,
+				 'what' :  Raptor.SetWhat,
+				 'tries' : Raptor.SetTries,
+				 'toolcheck' : Raptor.SetToolCheck,
+				 'timing' : Raptor.SetTiming,
+				 'source_target' : Raptor.AddSourceTarget,
+				 'command_file' : CommandFile,
+				 'parallel_parsing' : Raptor.SetParallelParsing,
+			 	 'version' : Raptor.PrintVersion
+				}
+
+	# Check if Quiet mode has been specified (otherwise we will make noise)
+	if parser.values.quiet:
+		Raptor.RunQuietly(True)
+
+	# some options imply that Raptor should exit immediately (e.g. --version)
+	keepGoing = True
+
+	if parser.values.version:
+		keepGoing = False
+
+	# Parse through the command line arguments passed, and call the
+	# corresponding function with the correct parameter.
+	# Since options is a OptParse.Value instance, it can be iterated over.
+	# This implementation helps avoid lengthy if-else statements
+	for opt in options.__dict__.items():
+		call_function = functions[str(opt[0])]
+		values = opt[1]
+		if not values:
+			pass
+		else:
+			if type(values) == types.ListType: # Check if the argument type is a list or a string. If list, then iterate through it and call the functions
+				for val in values:
+					keepGoing = (call_function(val) and keepGoing)
+			else:
+					keepGoing = (call_function(values) and keepGoing)
+
+	return keepGoing
+
+def CommandFile(file):
+	"this should never be called because we expand --command in this module."
+	print raptor.name + ": error: command file '%s' was not expanded" % file
+	return False
+
+
+
+
+# end of the raptor_cli module
+
+
--- a/sbsv2/raptor/python/raptor_data.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/raptor_data.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,1489 +1,1613 @@
-#
-# 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: 
-# raptor_data module
-# This module contains the classes that make up the Raptor Data Model.
-#
-
-import copy
-import generic_path
-import os
-import hashlib
-import raptor_utilities
-import re
-import types
-import sys
-import subprocess
-from tempfile import gettempdir
-from time import time, clock
-
-
-
-# What host platforms we recognise
-# This allows us to tie some variants to one host platform and some to another
-class HostPlatform(object):
-	""" List the host platforms on which we can build.  Allow configuration
- 	    files to specify different information based on that.
-	"""
-	hostplatforms = ["win32", "win64", "linux2"]
-	hostplatform = sys.platform
-
-	@classmethod
-	def IsKnown(cls, platformpattern):
-		"Does the parameter match the name of a known platform "
-		hpnre = re.compile(platformpattern, re.I)
-		for hp in cls.hostplatforms:
-			if hpnre.match(hp):
-				return True
-		return False
-
-	@classmethod
-	def IsHost(cls, platformpattern):
-		""" Does the parameter match the name of the
-		    platform that we're executing on? """
-		ppre = re.compile(platformpattern, re.I)
-		if ppre.match(cls.hostplatform):
-			return True
-		return False
-
-
-# Make sure not to start up on an unsupported platform
-if not HostPlatform.IsKnown(HostPlatform.hostplatform):
-	raise Exception("raptor_data module loaded on an unrecognised platform '%s'. Expected one of %s" % (hostplatform, str(hostplatforms)))
-
-
-# raptor_data module classes
-
-class Model(object):
-	"Base class for data-model objects"
-
-	def __init__(self):
-		self.owner = None	# Raptor object
-		self.source = None	# XML file
-		self.indent = " "	# for DebugPrint
-		self.host = None
-		self.cacheID = ""	# default set of cached objects
-
-
-	def SetOwner(self, aRaptor):
-		self.owner = aRaptor
-
-
-	def SetSourceFile(self, filename):
-		self.source = filename
-
-
-	def SetProperty(self, name, value):
-		raise InvalidPropertyError()
-
-
-	def AddChild(self, child):
-		raise InvalidChildError()
-
-
-	def DebugPrint(self, prefix = ""):
-		if self.owner:
-			self.owner.Debug("%s", prefix)
-
-	def Valid(self):
-		return False
-
-	def IsApplicable(self):
-		"This variant may be caused to only apply when used on a particular host build platform"
-		if self.host is None:
-			return True
-
-		if HostPlatform.IsHost(self.host):
-			return True
-
-		return False
-
-
-class InvalidPropertyError(Exception):
-	pass
-
-class InvalidChildError(Exception):
-	pass
-
-class BadReferenceError(Exception):
-	pass
-
-
-class Reference(Model):
-	"Base class for data-model reference objects"
-
-	def __init__(self, ref = None):
-		Model.__init__(self)
-		self.ref = ref
-		self.modifiers = []
-
-	def SetProperty(self, name, value):
-		if name == "ref":
-			self.ref = value
-		elif name == "mod":
-			self.modifiers = value.split(".")
-		else:
-			raise InvalidPropertyError()
-
-	def Resolve(self):
-		raise BadReferenceError()
-
-	def GetModifiers(self):
-		cache = self.owner.cache
-		return [ cache.FindNamedVariant(m) for m in self.modifiers ]
-
-	def Valid(self):
-		return self.ref
-
-
-class VariantContainer(Model):
-
-	def __init__(self):
-		Model.__init__(self)	# base class constructor
-		self.variants = []
-
-
-	def SetOwner(self, aRaptor):
-		Model.SetOwner(self, aRaptor)
-		for v in self.variants:
-			v.SetOwner(aRaptor)
-
-
-	def DebugPrint(self, prefix = ""):
-		for v in self.variants:
-			v.DebugPrint(prefix)
-
-
-	def AddVariant(self, variant):
-		if type(variant) is types.StringTypes:
-			variant = VariantRef(variant)
-
-
-		# Only add the variant if it's not in the list
-		# already
-		if not variant in self.variants:
-			self.variants.append(variant)
-
-	def GetVariants(self):
-		# resolve any VariantRef objects into Variant objects
-		for i,var in enumerate(self.variants):
-			if isinstance(var, Reference):
-				try:
-					self.variants[i] = var.Resolve()
-
-				except BadReferenceError:
-					self.owner.Error("Missing variant '%s'", var.ref)
-
-		return self.variants
-
-
-class Interface(Model):
-
-	def __init__(self, name = None):
-		Model.__init__(self)	# base class constructor
-		self.name = name
-		self.flm = None
-		self.abstract = False
-		self.extends = None
-		self.params = []
-		self.paramgroups = []
-
-	def DebugPrint(self, prefix = ""):
-		self.owner.Debug("%s<interface name='%s'>", prefix, self.name)
-		self.owner.Debug("%s...", prefix)
-		self.owner.Debug("%s</interface>", prefix)
-
-	def FindParent(self):
-		try:
-			return self.owner.cache.FindNamedInterface(self.extends, self.cacheID)
-		except KeyError:
-			raise BadReferenceError("Cannot extend interface because it cannot be found: "+str(self.extends))
-
-	def GetParams(self):
-		if self.extends != None:
-			parent = self.FindParent()
-
-			# what parameter names do we have already?
-			names = set([x.name for x in self.params])
-
-			# pick up ones we don't have that are in our parent
-			pp = []
-			for p in parent.GetParams():
-				if not p.name in names:
-					pp.append(p)
-
-			# list parent parameters first then ours
-			pp.extend(self.params)
-			return pp
-
-		return self.params
-
-	def GetParamGroups(self):
-		if self.extends != None:
-			parent = self.FindParent()
-
-			# what parameter names do we have already?
-			patterns = set([x.pattern for x in self.paramgroups])
-
-			# pick up ones we don't have that are in our parent
-			for g in parent.GetParamGroups():
-				if not g.pattern in patterns:
-					self.paramgroups.append(g)
-
-		return self.paramgroups
-
-
-	def GetFLMIncludePath(self):
-		"absolute path to the FLM"
-
-		if self.flm == None:
-			if self.extends != None:
-				parent = self.FindParent()
-
-				return parent.GetFLMIncludePath()
-			else:
-				raise InvalidPropertyError()
-
-		if not os.path.isabs(self.flm):
-			self.flm = os.path.join(os.path.dirname(self.source), self.flm)
-
-		return generic_path.Path(self.flm)
-
-
-	def SetProperty(self, name, value):
-		if name == "name":
-			self.name = value
-		elif name == "flm":
-			self.flm = value
-		elif name == "abstract":
-			self.abstract = (value == "true")
-		elif name == "extends":
-			self.extends = value
-		else:
-			raise InvalidPropertyError()
-
-
-	def AddChild(self, child):
-		if isinstance(child, Parameter):
-			self.AddParameter(child)
-		elif isinstance(child, ParameterGroup):
-			self.AddParameterGroup(child)
-		else:
-			raise InvalidChildError()
-
-
-	def AddParameter(self, parameter):
-		self.params.append(parameter)
-
-	def AddParameterGroup(self, parametergroup):
-		self.paramgroups.append(parametergroup)
-
-	def Valid(self):
-		return (self.name != None)
-
-
-class InterfaceRef(Reference):
-
-	def DebugPrint(self, prefix = ""):
-		self.owner.Debug("%s<interfaceRef ref='%s'/>", prefix, self.ref)
-
-	def Resolve(self):
-		try:
-			return self.owner.cache.FindNamedInterface(self.ref, self.cacheID)
-		except KeyError:
-			raise BadReferenceError()
-
-
-class Specification(VariantContainer):
-
-	def __init__(self, name = "", type = ""):
-		VariantContainer.__init__(self)	# base class constructor
-		self.name = name
-		self.type = type
-		self.interface = None
-		self.childSpecs = []
-		self.parentSpec = None
-
-
-	def DebugPrint(self, prefix = ""):
-		self.owner.Debug("%s<spec name='%s'>", prefix, self.name)
-		if self.interface:
-			self.interface.DebugPrint(prefix + self.indent)
-		VariantContainer.DebugPrint(self, prefix + self.indent)
-		for c in self.childSpecs:
-			c.DebugPrint(prefix + self.indent)
-		self.owner.Debug("%s</spec>", prefix)
-
-
-	def SetOwner(self, aRaptor):
-		VariantContainer.SetOwner(self, aRaptor)
-
-		if self.interface != None:
-			self.interface.SetOwner(aRaptor)
-
-		for s in self.childSpecs:
-			s.SetOwner(aRaptor)
-
-
-	def SetProperty(self, name, value):
-		if name == "name":
-			self.name = value
-		else:
-			raise InvalidPropertyError()
-
-
-	def Configure(self, config):
-		# configure all the children (some may be Filters or parents of)
-		for spec in self.GetChildSpecs():
-			spec.Configure(config)
-
-
-	def HasInterface(self):
-		return self.interface != None
-
-
-	def SetInterface(self, interface):
-		if isinstance(interface, Interface) \
-		or isinstance(interface, InterfaceRef):
-			self.interface = interface
-		else:
-			self.interface = InterfaceRef(interface)
-
-
-	def GetInterface(self):
-		"""return the Interface (fetching from the cache if it was a ref)
-		may return None"""
-
-		if self.interface == None \
-		or isinstance(self.interface, Interface):
-			return self.interface
-
-		if isinstance(self.interface, InterfaceRef):
-			try:
-				self.interface = self.interface.Resolve()
-				return self.interface
-
-			except BadReferenceError:
-				self.owner.Error("Missing interface %s", self.interface.ref)
-				return None
-
-
-	def AddChild(self, child):
-		if isinstance(child, Specification):
-			self.AddChildSpecification(child)
-		elif isinstance(child, Interface) \
-		  or isinstance(child, InterfaceRef):
-			self.SetInterface(child)
-		elif isinstance(child, Variant) \
-		  or isinstance(child, VariantRef):
-			self.AddVariant(child)
-		else:
-			raise InvalidChildError()
-
-
-	def AddChildSpecification(self, child):
-		child.SetParentSpec(self)
-		self.childSpecs.append(child)
-
-
-	def SetParentSpec(self, parent):
-		self.parentSpec = parent
-
-
-	def GetChildSpecs(self):
-		return self.childSpecs
-
-
-	def Valid(self):
-		return True
-
-
-	def GetAllVariantsRecursively(self):
-		"""Returns all variants contained in this node and in its ancestors.
-
-		The returned value is a list, the structure of which is [variants-in-parent,
-		variants-in-self].
-
-		Note that the function recurses through parent *Specifications*, not through
-		the variants themselves.
-		"""
-		if self.parentSpec:
-			variants = self.parentSpec.GetAllVariantsRecursively()
-		else:
-			variants = []
-
-		variants.extend( self.GetVariants() )
-
-		return variants
-
-
-class Filter(Specification):
-	"""A Filter is two Specification nodes and a True/False switch.
-
-	Filter extends Specification to have two nodes, only one of
-	which can be active at any time. Which node is active is determined
-	when the Configure method is called after setting up a Condition.
-
-	If several Conditions are set, the test is an OR of all of them."""
-
-	def __init__(self, name = ""):
-		Specification.__init__(self, name)	# base class constructor
-		self.Else = Specification(name)     # same for Else part
-		self.isTrue = True
-		self.configNames = set()            #
-		self.variableNames = set()          # TO DO: Condition class
-		self.variableValues = {}            #
-
-	def DebugPrint(self, prefix = ""):
-		self.owner.Debug("%s<filter name='%s'>", prefix, self.name)
-		self.owner.Debug("%s <if config='%s'>", prefix, " | ".join(self.configNames))
-		Specification.DebugPrint(self, prefix + self.indent)
-		self.owner.Debug("%s </if>", prefix)
-		self.owner.Debug("%s <else>", prefix)
-		self.Else.DebugPrint(prefix + self.indent)
-		self.owner.Debug("%s </else>", prefix)
-		self.owner.Debug("%s</filter>", prefix)
-
-
-	def SetConfigCondition(self, configName):
-		self.configNames = set([configName])
-
-	def AddConfigCondition(self, configName):
-		self.configNames.add(configName)
-
-
-	def SetVariableCondition(self, variableName, variableValues):
-		self.variableNames = set([variableName])
-		if type(variableValues) == types.ListType:
-			self.variableValues[variableName] = set(variableValues)
-		else:
-			self.variableValues[variableName] = set([variableValues])
-
-	def AddVariableCondition(self, variableName, variableValues):
-		self.variableNames.add(variableName)
-		if type(variableValues) == types.ListType:
-			self.variableValues[variableName] = set(variableValues)
-		else:
-			self.variableValues[variableName] = set([variableValues])
-
-
-	def Configure(self, buildUnit):
-		self.isTrue = False
-
-		if buildUnit.name in self.configNames:
-			self.isTrue = True
-		elif self.variableNames:
-			evaluator = self.owner.GetEvaluator(self.parentSpec, buildUnit)
-
-			for variableName in self.variableNames:
-				variableValue = evaluator.Get(variableName)
-
-				if variableValue in self.variableValues[variableName]:
-					self.isTrue = True
-					break
-
-		# configure all the children too
-		for spec in self.GetChildSpecs():
-			spec.Configure(buildUnit)
-
-
-	def SetOwner(self, aRaptor):
-		# base class method
-		Specification.SetOwner(self, aRaptor)
-		# same for Else part
-		self.Else.SetOwner(aRaptor)
-
-
-	def HasInterface(self):
-		if self.isTrue:
-			return Specification.HasInterface(self)
-		else:
-			return self.Else.HasInterface()
-
-
-	def GetInterface(self):
-		if self.isTrue:
-			return Specification.GetInterface(self)
-		else:
-			return self.Else.GetInterface()
-
-
-	def GetVariants(self):
-		if self.isTrue:
-			return Specification.GetVariants(self)
-		else:
-			return self.Else.GetVariants()
-
-
-	def SetParentSpec(self, parent):
-		# base class method
-		Specification.SetParentSpec(self, parent)
-		# same for Else part
-		self.Else.SetParentSpec(parent)
-
-
-	def GetChildSpecs(self):
-		if self.isTrue:
-			return Specification.GetChildSpecs(self)
-		else:
-			return self.Else.GetChildSpecs()
-
-
-class Parameter(Model):
-
-	def __init__(self, name = None, default = None):
-		Model.__init__(self)	# base class constructor
-		self.name = name
-		self.default = default
-
-
-	def SetProperty(self, name, value):
-		if name == "name":
-			self.name = value
-		elif name == "default":
-			self.default = value
-		else:
-			raise InvalidPropertyError()
-
-
-	def Valid(self):
-		return (self.name != None)
-
-class ParameterGroup(Model):
-	"""A group of Parameters specified in an interface by a regexp"""
-	def __init__(self, pattern = None, default = None):
-		Model.__init__(self)	# base class constructor
-		self.pattern = pattern
-
-		self.patternre = None
-		if pattern:
-			try:
-				self.patternre = re.compile(pattern)
-			except TypeError:
-				pass
-		self.default = default
-
-
-	def SetProperty(self, pattern, value):
-		if pattern == "pattern":
-			self.pattern = value
-			self.patternre = re.compile(value)
-		elif pattern == "default":
-			self.default = value
-		else:
-			raise InvalidPropertyError()
-
-
-	def Valid(self):
-		return (self.pattern != None and self.patternre != None)
-
-
-class Operation(Model):
-	"Base class for variant operations"
-	def __init__(self):
-		Model.__init__(self)	# base class constructor
-		self.type = None
-
-
-	def Apply(self, oldValue):
-		pass
-
-
-class Append(Operation):
-	__slots__ = ('name','value','separator','owner')
-
-	def __init__(self, name = None, value = None, separator = " "):
-		Operation.__init__(self)	# base class constructor
-		self.name = name
-		self.value = value
-		self.separator = separator
-
-
-	def DebugPrint(self, prefix = ""):
-		attributes = "name='" + self.name + "' value='" + self.value + "' separator='" + self.separator + "'"
-		self.owner.Debug("%s<append %s/>", prefix, attributes)
-
-
-	def Apply(self, oldValue):
-		if len(oldValue) > 0:
-			if len(self.value) > 0:
-				return oldValue + self.separator + self.value
-			else:
-				return oldValue
-		else:
-			return self.value
-
-
-	def SetProperty(self, name, value):
-		if name == "name":
-			self.name = value
-		elif name == "value":
-			self.value = value
-		elif name == "separator":
-			self.separator = value
-		else:
-			raise InvalidPropertyError()
-
-
-	def Valid(self):
-		return (self.name != None and self.value != None)
-
-
-class Prepend(Operation):
-	def __init__(self, name = None, value = None, separator = " "):
-		Operation.__init__(self)	# base class constructor
-		self.name = name
-		self.value = value
-		self.separator = separator
-
-
-	def DebugPrint(self, prefix = ""):
-		attributes = "name='" + self.name + "' value='" + self.value + "' separator='" + self.separator + "'"
-		self.owner.Debug("%s<prepend %s/>", prefix, attributes)
-
-
-	def Apply(self, oldValue):
-		if len(oldValue) > 0:
-			if len(self.value) > 0:
-				return self.value + self.separator + oldValue
-			else:
-				return oldValue
-		else:
-			return self.value
-
-
-	def SetProperty(self, name, value):
-		if name == "name":
-			self.name = value
-		elif name == "value":
-			self.value = value
-		elif name == "separator":
-			self.separator = value
-		else:
-			raise InvalidPropertyError()
-
-
-	def Valid(self):
-		return (self.name != None and self.value != None)
-
-
-class Set(Operation):
-	"""implementation of <set> operation"""
-	__slots__ = ('name','value', 'type', 'versionCommand', 'versionResult', 'owner')
-
-	def __init__(self, name = None, value = "", type = ""):
-		Operation.__init__(self)	# base class constructor
-		self.name = name
-		self.value = value
-		self.type = type
-		self.versionCommand = ""
-		self.versionResult = ""
-
-
-	def DebugPrint(self, prefix = ""):
-		attributes = "name='" + self.name + "' value='" + self.value + "' type='" + self.type + "'"
-		if type == "tool":
-			attributes += " versionCommand='" + self.versionCommand + "' versionResult='" + self.versionResult
-
-		self.owner.Debug("%s<set %s/>", prefix, attributes)
-
-
-	def Apply(self, oldValue):
-		return self.value
-
-
-	def SetProperty(self, name, value):
-		if name == "name":
-			self.name = value
-		elif name == "value":
-			self.value = value
-		elif name == "type":
-			self.type = value
-		elif name == "versionCommand":
-			self.versionCommand = value
-		elif name == "versionResult":
-			self.versionResult = value
-		elif name == "host":
-			if HostPlatform.IsKnown(value):
-				self.host = value
-		else:
-			raise InvalidPropertyError()
-
-
-	def Valid(self):
-		return (self.name != None and self.value != None)
-
-
-class Env(Set):
-	"""implementation of <env> operator"""
-
-	def __init__(self, name = None, default = None, type = ""):
-		Set.__init__(self, name, "", type)	# base class constructor
-		self.default = default
-
-
-	def DebugPrint(self, prefix = ""):
-		attributes = "name='" + self.name + "' type='" + self.type + "'"
-		if default != None:
-			attributes += " default='" + self.default + "'"
-
-		if type == "tool":
-			attributes += " versionCommand='" + self.versionCommand + "' versionResult='" + self.versionResult + "'"
-
-		self.owner.Debug("%s<env %s/>", prefix, attributes)
-
-
-	def Apply(self, oldValue):
-		try:
-			value = os.environ[self.name]
-
-			# if this value is a "path" or a "tool" then we need to make sure
-			# it is a proper absolute path in our preferred format.
-			if value and (self.type == "path" or self.type == "tool"):
-				try:
-					path = generic_path.Path(value)
-					value = str(path.Absolute())
-				except ValueError,e:
-					self.owner.Error("the environment variable %s is incorrect: %s" % (self.name, str(e)))
-					return "NO_VALUE_FOR_" + self.name
-		except KeyError:
-			if self.default != None:
-				value = self.default
-			else:
-				self.owner.Error("%s is not set in the environment and has no default", self.name)
-				return "NO_VALUE_FOR_" + self.name
-
-		return value
-
-
-	def SetProperty(self, name, value):
-		if name == "default":
-			self.default = value
-		else:
-			Set.SetProperty(self, name, value)
-
-
-	def Valid(self):
-		return (self.name != None)
-
-
-class BuildUnit(object):
-	"Represents an individual buildable unit."
-
-	def __init__(self, name, variants):
-		self.name = name
-		
-		# A list of Variant objects.
-		self.variants = variants
-
-		# Cache for the variant operations implied by this BuildUnit.
-		self.operations = []
-		self.variantKey = ""
-
-	def GetOperations(self):
-		"""Return all operations related to this BuildUnit.
-		
-		The result is cached, and so will only be computed once per BuildUnit.
-		"""
-		key = '.'.join([x.name for x in self.variants])
-		if self.variantKey != key:
-			self.variantKey = key
-			for v in self.variants:
-				self.operations.extend( v.GetAllOperationsRecursively() )
-
-		return self.operations
-
-class Config(object):
-	"""Abstract type representing an argument to the '-c' option.
-
-	The fundamental property of a Config is that it can generate one or more
-	BuildUnits.
-	"""
-
-	def __init__(self):
-		self.modifiers = []
-
-	def AddModifier(self, variant):
-		self.modifiers.append(variant)
-
-	def ClearModifiers(self):
-		self.modifiers = []
-
-	def GenerateBuildUnits(self):
-		"""Returns a list of BuildUnits.
-
-		This function must be overridden by derived classes.
-		"""
-		raise NotImplementedError()
-
-
-class Variant(Model, Config):
-
-	def __init__(self, name = ""):
-		Model.__init__(self)
-		Config.__init__(self)
-		self.name = name
-
-		# Operations defined inside this variant.
-		self.ops = []
-
-		# The name of our parent variant, if any.
-		self.extends = ""
-
-		# Any variant references used inside this variant.
-		self.variantRefs = []
-
-		self.allOperations = []
-
-	def SetProperty(self, name, value):
-		if name == "name":
-			self.name = value
-		elif name == "host":
-			if HostPlatform.IsKnown(value):
-				self.host = value
-		elif name == "extends":
-			self.extends = value
-		else:
-			raise InvalidPropertyError()
-
-	def AddChild(self, child):
-		if isinstance(child, Operation):
-			self.ops.append(child)
-		elif isinstance(child, VariantRef):
-			self.variantRefs.append(child)
-		else:
-			raise InvalidChildError()
-
-	def Valid(self):
-		return self.name
-
-	def SetOwner(self, aRaptor):
-
-		Model.SetOwner(self, aRaptor)
-
-		for r in self.variantRefs:
-			r.SetOwner(aRaptor)
-
-		for op in self.ops:
-			op.SetOwner(aRaptor)
-
-	def AddOperation(self, op):
-		self.ops.append(op)
-
-	def GetAllOperationsRecursively(self):
-		"""Returns a list of all operations in this variant.
-
-		The list elements are themselves lists; the overall structure of the
-		returned value is:
-
-		[ [ops-from-parent],[ops-from-varRefs], [ops-in-self] ]
-		"""
-
-		if not self.allOperations:
-			if self.extends:
-				parent = self.owner.cache.FindNamedVariant(self.extends)
-				self.allOperations.extend( parent.GetAllOperationsRecursively() )
-			for r in self.variantRefs:
-				for v in [ r.Resolve() ] + r.GetModifiers():
-					self.allOperations.extend( v.GetAllOperationsRecursively() )
-			self.allOperations.append(self.ops)
-
-		return self.allOperations
-
-	def GenerateBuildUnits(self):
-
-		name = self.name
-		vars = [self]
-
-		for m in self.modifiers:
-			name = name + "." + m.name
-			vars.append(m)
-
-		return [ BuildUnit(name, vars) ]
-
-	def DebugPrint(self, prefix = ""):
-
-		self.owner.Debug("%s<var name='%s' extends='%s'>", prefix, self.name, self.extends)
-		for op in self.ops:
-			op.DebugPrint(prefix + self.indent)
-
-		self.owner.Debug("%s</var>", prefix)
-
-
-class VariantRef(Reference):
-
-	def __init__(self, ref=None):
-		Reference.__init__(self, ref)
-
-	def DebugPrint(self, prefix = ""):
-		self.owner.Debug("%s<varRef ref='%s'/>", prefix, self.ref)
-
-	def Resolve(self):
-		try:
-			return self.owner.cache.FindNamedVariant(self.ref)
-		except KeyError:
-			raise BadReferenceError(self.ref)
-
-
-class Alias(Model, Config):
-
-	def __init__(self, name=""):
-		Model.__init__(self)
-		Config.__init__(self)
-		self.name = name
-		self.meaning = ""
-		self.varRefs = []
-		self.variants = []
-
-	def DebugPrint(self, prefix = ""):
-		self.owner.Debug("%s<alias name='%s' meaning='%s'/>", prefix, self.name, self.meaning)
-
-	def SetProperty(self, key, val):
-		if key == "name":
-			self.name = val
-		elif key == "meaning":
-			self.meaning = val
-
-			for u in val.split("."):
-				self.varRefs.append( VariantRef(u) )
-		else:
-			raise InvalidPropertyError()
-
-	def SetOwner(self, raptor):
-		Model.SetOwner(self, raptor)
-		for r in self.varRefs:
-			r.SetOwner(raptor)
-
-	def Valid(self):
-		return self.name and self.meaning
-
-	def GenerateBuildUnits(self):
-		if not self.variants:
-			for r in self.varRefs:
-				try:
-					self.variants.append( r.Resolve() )
-				except BadReferenceError:
-					self.owner.Error("Missing variant '%s'", r.ref)
-
-		name = self.name
-
-		for v in self.modifiers:
-			name = name + "." + v.name
-
-		return [ BuildUnit(name, self.variants + self.modifiers) ]
-
-
-class AliasRef(Reference):
-
-	def __init__(self, ref=None):
-		Reference.__init__(self, ref)
-
-	def DebugPrint(self, prefix = ""):
-		self.owner.Debug("%s<aliasRef ref='%s'/>", prefix, self.ref)
-
-	def Resolve(self):
-		try:
-			return self.owner.cache.FindNamedAlias(self.ref)
-		except KeyError:
-			raise BadReferenceError(self.ref)
-
-
-class Group(Model, Config):
-	def __init__(self, name=""):
-		Model.__init__(self)
-		Config.__init__(self)
-		self.name = name
-		self.childRefs = []
-
-	def SetProperty(self, key, val):
-		if key == "name":
-			self.name = val
-		else:
-			raise InvalidPropertyError()
-
-	def AddChild(self, child):
-		if isinstance( child, (VariantRef,AliasRef,GroupRef) ):
-			self.childRefs.append(child)
-		else:
-			raise InvalidChildError()
-
-	def SetOwner(self, raptor):
-		Model.SetOwner(self, raptor)
-		for r in self.childRefs:
-			r.SetOwner(raptor)
-
-	def Valid(self):
-		return self.name and self.childRefs
-
-	def DebugPrint(self, prefix = ""):
-
-		self.owner.Debug("<group name='%s'>", prefix, self.name)
-
-		for r in self.childRefs:
-			r.DebugPrint(prefix + self.indent)
-
-		self.owner.Debug("%s</group>", prefix)
-
-	def GenerateBuildUnits(self):
-
-		units = []
-
-		for r in self.childRefs:
-			refMods = r.GetModifiers()
-
-			try:
-				obj = r.Resolve()
-			except BadReferenceError:
-				self.owner.Error("Missing variant '%s'", r.ref)
-			else:
-				obj.ClearModifiers()
-
-				for m in refMods + self.modifiers:
-					obj.AddModifier(m)
-
-				units.extend( obj.GenerateBuildUnits() )
-
-		return units
-
-
-class GroupRef(Reference):
-
-	def __init__(self, ref=None):
-		Reference.__init__(self, ref)
-
-	def DebugPrint(self, prefix = ""):
-		mod = ".".join(self.modifiers)
-		self.owner.Debug("%s<groupRef ref='%s' mod='%s'/>", prefix, self.ref, mod)
-
-	def Resolve(self):
-		try:
-			return self.owner.cache.FindNamedGroup(self.ref)
-		except KeyError:
-			raise BadReferenceError(self.ref)
-
-class Tool(object):
-	"""Represents a tool that might be used by raptor e.g. a compiler"""
-
-	# For use in dealing with tools that return non-ascii version strings.
-	nonascii = ""
-	identity_chartable = chr(0)
-	for c in xrange(1,128):
-		identity_chartable += chr(c)
-	for c in xrange(128,256):
-		nonascii += chr(c)
-		identity_chartable += " "
-
-	def __init__(self, name, command, versioncommand, versionresult, id="", log = raptor_utilities.nulllog):
-		self.name = name
-		self.command = command
-		self.versioncommand = versioncommand
-		self.versionresult = versionresult
-		self.id = id # what config this is from - used in debug messages
-		self.date = None
-
-
-		# Assume the tool is unavailable or the wrong
-		# version until someone proves that it's OK
-		self.valid = False
-
-		self.log=log
-
-	def expand(self, toolset):
-		self.versioncommand = toolset.ExpandAll(self.versioncommand)
-		self.versionresult  = toolset.ExpandAll(self.versionresult)
-		self.command = toolset.ExpandAll(self.command)
-		self.key = hashlib.md5(self.versioncommand + self.versionresult).hexdigest()
-		
-		# We need the tool's date to find out if we should check it.
-		try:
-			if '/' in self.command:
-				testfile = os.path.abspath(self.command.strip("\"'"))
-			else:
-				# The tool isn't a relative or absolute path so the could be relying on the 
-				# $PATH variable to make it available.  We must find the tool if it's a simple 
-				# executable file (e.g. "armcc" rather than "python myscript.py") then get it's date. 
-				# We can use the date later to see if our cache is valid. 
-				# If it really is not a simple command then we won't be able to get a date and
-				# we won't be able to tell if it is altered or updated - too bad!
-				testfile = generic_path.Where(self.command)
-				self.log.Debug("toolcheck: tool '%s' was found on the path at '%s' ", self.command, testfile)
-				if testfile is None:
-					raise Exception("Can't be found in path")
-
-			if not os.path.isfile(testfile):
-				raise Exception("tool %s appears to not be a file %s", self.command, testfile)
-				
-			testfile_stat = os.stat(testfile)
-			self.date = testfile_stat.st_mtime
-		except Exception,e:
-			self.log.Debug("toolcheck: '%s=%s' cannot be dated - this is ok, but the toolcheck won't be able to tell when a new  of the tool is installed. (%s)", self.name, self.command, str(e))
-	
-			
-	def check(self, shell, evaluator):
-
-		self.vre = re.compile(self.versionresult)
-
-		try:
-			self.log.Debug("Pre toolcheck: '%s' for version '%s'", self.name, self.versionresult)
-			p = subprocess.Popen(args=[shell, "-c", self.versioncommand], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
-			versionoutput,err = p.communicate()
-			self.log.Debug("Checking tool '%s' for version '%s'", self.name, self.versionresult)
-		except Exception,e:
-			versionoutput=None
-
-		# Some tools return version strings with unicode characters! 
-		# There is no good response other than a lot of decoding and encoding.
-		# Simpler to ignore it:
-		versionoutput_a = versionoutput.translate(Tool.identity_chartable,"")
-
-		if versionoutput_a and self.vre.search(versionoutput_a) != None:
-			self.log.Debug("tool '%s' returned an acceptable version '%s' at %s", self.name, versionoutput_a, str(self.date))
-			self.valid = True
-		else:
-			self.log.Error("tool '%s' from config '%s' did not return version '%s' as required.\nCommand '%s' returned:\n%s\nCheck your environment and configuration.\n", self.name, self.id, self.versionresult, self.versioncommand, versionoutput_a)
-			self.valid = False
-		return self.valid
-
-def envhash(irrelevant_vars):
-	"""Determine something unique about this environment to identify it.
-	must ignore variables that change without mattering to the caller
-	e.g. perhaps PATH matters but PWD and PPID don't"""
-	envid = hashlib.md5()
-	for k in os.environ:
-		if k not in irrelevant_vars:
-			envid.update(os.environ[k])
-	return envid.hexdigest()[:16]
-
-
-class ToolSet(object):
-	""" 
-	This class manages a bunch of tools and keeps a cache of
-	all tools that it ever sees (across all configurations).
-	toolset.check() is called for each config but the cache is kept across calls to
-	catch the use of one tool in many configs.
-	write() is used to flush the cache to disc.
-	"""
-	# The raptor shell - this is not mutable.
-	hostbinaries = os.path.join(os.environ['SBS_HOME'], 
-	                            os.environ['HOSTPLATFORM_DIR'])
-	                            
-	if HostPlatform.IsHost('lin*'):
-		shell=os.path.join(hostbinaries, 'bin/bash')
-	else:
-		if 'SBS_CYGWIN' in os.environ:
-			shell=os.path.join(os.environ['SBS_CYGWIN'], 'bin\\bash.exe')
-		else:
-			shell=os.path.join(hostbinaries, 'cygwin\\bin\\bash.exe')
-
-
-	irrelevant_vars = ['PWD','OLDPWD','PID','PPID', 'SHLVL' ]
-
-
-	shell_version=".*GNU bash, version [34].*"
-	shell_re = re.compile(shell_version)
-	if 'SBS_BUILD_DIR' in os.environ:
-		cachefile_basename = str(generic_path.Join(os.environ['SBS_BUILD_DIR'],"toolcheck_cache_"))
-	elif 'EPOCROOT' in os.environ:
-		cachefile_basename = str(generic_path.Join(os.environ['EPOCROOT'],"epoc32/build/toolcheck_cache_"))
-	else:
-		cachefile_basename = None
-
-	tool_env_id = envhash(irrelevant_vars)
-	filemarker = "sbs_toolcache_2.8.2"
-
-	def __init__(self, log = raptor_utilities.nulllog, forced=False):
-		self.__toolcheckcache = {}
-
-		self.valid = True
-		self.checked = False
-		self.shellok = False
-		self.configname=""
-		self.cache_loaded = False
-		self.forced = forced
-
-		self.log=log
-
-		# Read in the tool cache
-		#
-		# The cache format is a hash key which identifies the
-		# command and the version that we're checking for. Then
-		# there are name,value pairs that record, e.g. the date
-		# of the command file or the name of the variable that
-		# the config uses for the tool (GNUCP or MWCC or whatever)
-
-		if ToolSet.cachefile_basename:
-			self.cachefilename = ToolSet.cachefile_basename+".tmp"
-			if not self.forced:
-				try:
-					f = open(self.cachefilename, "r+")
-					# if this tool cache was recorded in
-					# a different environment then ignore it.
-					marker = f.readline().rstrip("\r\n")
-					if marker == ToolSet.filemarker:
-						env_id_tmp = f.readline().rstrip("\r\n")
-						if env_id_tmp == ToolSet.tool_env_id:
-							try:
-								for l in f.readlines():
-									toolhistory  = l.rstrip(",\n\r").split(",")
-									ce = {}
-									for i in toolhistory[1:]:
-										(name,val) = i.split("=")
-										if name == "valid":
-											val = bool(val)
-										elif name == "age":
-											val = int(val)
-										elif name == "date":
-											if val != "None":
-												val = float(val)
-											else:
-												val= None
-
-										ce[name] = val
-									self.__toolcheckcache[toolhistory[0]] = ce
-								log.Info("Loaded toolcheck cache: %s\n", self.cachefilename)
-							except Exception, e:
-								log.Info("Ignoring garbled toolcheck cache: %s (%s)\n", self.cachefilename, str(e))
-								self.__toolcheckcache = {}
-								
-									
-						else:
-							log.Info("Toolcheck cache %s ignored - environment changed\n", self.cachefilename)
-					else:
-						log.Info("Toolcheck cache not loaded = marker missing: %s %s\n", self.cachefilename, ToolSet.filemarker)
-					f.close()
-				except IOError, e:
-					log.Info("Failed to load toolcheck cache: %s\n", self.cachefilename)
-		else:
-			log.Debug("Toolcheck cachefile not created because EPOCROOT not set in environment.\n")
-
-	def check_shell(self):
-		# The command shell is a critical tool because all the other tools run
-		# within it so we must check for it first. It has to be in the path.
-		# bash 4 is preferred, 3 is accepted
-		try:
-			p = subprocess.Popen(args=[ToolSet.shell, '--version'], bufsize=1024, shell = False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
-			shellversion_out, errtxt = p.communicate()
-			if ToolSet.shell_re.search(shellversion_out) == None:
-				self.log.Error("A critical tool, '%s', did not return the required version '%s':\n%s\nPlease check that '%s' is in the path.", ToolSet.shell, ToolSet.shell_version, shellversion_out, ToolSet.shell)
-				self.valid = False
-		except Exception,e:
-			self.log.Error("A critical tool could not be found.\nPlease check that '%s' is in the path. (%s)", ToolSet.shell,  str(e))
-			self.valid = False
-
-		return self.valid
-
-	def check(self, evaluator, configname):
-		"""Check the toolset for a particular config"""
-
-		self.checked = True # remember that we did check something
-
-		if not self.shellok:
-			self.shellok = self.check_shell()
-		self.shellok = True
-
-		self.valid = self.valid and self.shellok
-
-		cache = self.__toolcheckcache 
-		for tool in evaluator.tools:
-			if not self.forced:
-				try:
-					t = cache[tool.key]
-						
-				except KeyError,e:
-					pass
-				else:
-					# if the cache has an entry for the tool then see if the date on
-					# the tool has changed (assuming the tool is a simple executable file)
-					if t.has_key('date') and (tool.date is None or (tool.date - t['date'] > 0.1))  :
-						self.log.Debug("toolcheck forced: '%s'  changed since the last check: %s < %s", tool.command, str(t['date']), str(tool.date))
-					else:
-						t['age'] = 0 # we used it so it's obviously needed
-						self.valid = self.valid and t['valid']
-						self.log.Debug("toolcheck saved on: '%s'", tool.name)
-						continue
-
-
-			self.log.Debug("toolcheck done: %s -key: %s" % (tool.name, tool.key))
-
-			if not tool.check(ToolSet.shell, evaluator):
-				self.valid = False
-
-			# Tool failures are cached just like successes - don't want to repeat them
-			cache[tool.key] =  { "name" : tool.name, "valid" : tool.valid, "age" : 0 , "date" : tool.date }
-
-
-	def write(self):
-		"""Writes the tool check cache to disc.
-
-		   toolset.write()
-		"""
-		cache = self.__toolcheckcache 
-
-		# Write out the cache.
-		if self.checked and ToolSet.cachefile_basename:
-			self.log.Debug("Saving toolcache: %s", self.cachefilename)
-			try:
-				f = open(self.cachefilename, "w+")
-				f.write(ToolSet.filemarker+"\n")
-				f.write(ToolSet.tool_env_id+"\n")
-				for k,ce in cache.iteritems():
-
-					# If a tool has not been used for an extraordinarily long time
-					# then forget it - to prevent the cache from clogging up with old tools.
-					# Only write entries for tools that were found to be ok - so that the 
-					# next time the ones that weren't will be re-tested
-
-					if ce['valid'] and ce['age'] < 100:
-						ce['age'] += 1
-						f.write("%s," % k)
-						for n,v in ce.iteritems():
-							f.write("%s=%s," % (n,str(v)))
-					f.write("\n")
-				f.close()
-				self.log.Info("Created/Updated toolcheck cache: %s\n", self.cachefilename)
-			except Exception, e:
-				self.log.Info("Could not write toolcheck cache: %s", str(e))
-		return self.valid
-
-
-class Evaluator(object):
-	"""Determine the values of variables under different Configurations.
-	Either of specification and buildUnit may be None."""
-
-
-	refRegex = re.compile("\$\((.+?)\)")
-
-	def __init__(self, Raptor, specification, buildUnit, gathertools = False):
-		self.raptor = Raptor
-		self.dict = {}
-		self.tools = []
-		self.gathertools = gathertools
-
-		specName = "none"
-		configName = "none"
-
-		# A list of lists of operations.
-		opsLists = []
-
-		if buildUnit:
-			opsLists.extend( buildUnit.GetOperations() )
-
-		if specification:
-			for v in specification.GetAllVariantsRecursively():
-				opsLists.extend( v.GetAllOperationsRecursively() )
-
-		tools = {}
-
-		for opsList in opsLists:
-			for op in opsList:
-				# applying an Operation to a non-existent variable
-				# is OK. We assume that it is just an empty string.
-				try:
-					oldValue = self.dict[op.name]
-				except KeyError:
-					oldValue = ""
-
-				newValue = op.Apply(oldValue)
-				self.dict[op.name] = newValue
-			
-				if self.gathertools:
-					if op.type == "tool" and op.versionCommand and op.versionResult:
-						tools[op.name] = Tool(op.name, newValue, op.versionCommand, op.versionResult, configName, log = self.raptor)
-
-
-		if self.gathertools:
-			self.tools = tools.values()
-		else:
-			self.tools=[]
-
-		# resolve inter-variable references in the dictionary
-		unresolved = True
-
-		for k, v in self.dict.items():
-			self.dict[k] = v.replace("$$","__RAPTOR_ESCAPED_DOLLAR__")
-
-		while unresolved:
-			unresolved = False
-			for k, v in self.dict.items():
-				if v.find('$(' + k + ')') != -1:
-					self.raptor.Error("Recursion Detected in variable '%s' in configuration '%s' ",k,configName)
-					expanded = "RECURSIVE_INVALID_STRING"
-				else:
-					expanded = self.ExpandAll(v, specName, configName)
-
-				if expanded != v:				# something changed?
-					self.dict[k] = expanded
-					unresolved = True			# maybe more to do
-
-		# unquote double-dollar references
-		for k, v in self.dict.items():
-			self.dict[k] = v.replace("__RAPTOR_ESCAPED_DOLLAR__","$")
-
-		for t in self.tools:
-			t.expand(self)
-
-
-
-	def Get(self, name):
-		"""return the value of variable 'name' or None if not found."""
-
-		if name in self.dict:
-			return self.dict[name]
-		else:
-			return None
-
-
-	def Resolve(self, name):
-		"""same as Get except that env variables are expanded.
-
-		raises BadReferenceError if the variable 'name' exists but a
-		contained environment variable does not exist."""
-		return self.Get(name) # all variables are now expanded anyway
-
-
-	def ResolveMatching(self, pattern):
-		""" Return a dictionary of all variables that match the pattern """
-		for k,v in self.dict.iteritems():
-			if pattern.match(k):
-				yield (k,v)
-
-
-	def ExpandAll(self, value, spec = "none", config = "none"):
-		"""replace all $(SOMETHING) in the string value.
-
-		returns the newly expanded string."""
-
-		refs = Evaluator.refRegex.findall(value)
-
-		for r in set(refs):
-			expansion = None
-
-			if r in self.raptor.override:
-				expansion = self.raptor.override[r]
-			elif r in self.dict:
-				expansion = self.dict[r]
-			else:
-				# no expansion for $(r)
-				self.raptor.Error("Unset variable '%s' used in spec '%s' with config '%s'",
-							  	  r, spec, config)
-			if expansion != None:
-				value = value.replace("$(" + r + ")", expansion)
-
-		return value
-
-
-# raptor_data module functions
-
-
-# end of the raptor_data module
+#
+# 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: 
+# raptor_data module
+# This module contains the classes that make up the Raptor Data Model.
+#
+
+import copy
+import generic_path
+import os
+import hashlib
+import raptor_utilities
+import re
+import types
+import sys
+import subprocess
+from tempfile import gettempdir
+from time import time, clock
+import traceback
+import raptor_cache
+
+
+class MissingInterfaceError(Exception):
+	def __init__(self, s):
+		Exception.__init__(self,s)
+
+# What host platforms we recognise
+# This allows us to tie some variants to one host platform and some to another
+class HostPlatform(object):
+	""" List the host platforms on which we can build.  Allow configuration
+ 	    files to specify different information based on that.
+	"""
+	hostplatforms = ["win32", "win64", "linux2"]
+	hostplatform = sys.platform
+
+	@classmethod
+	def IsKnown(cls, platformpattern):
+		"Does the parameter match the name of a known platform "
+		hpnre = re.compile(platformpattern, re.I)
+		for hp in cls.hostplatforms:
+			if hpnre.match(hp):
+				return True
+		return False
+
+	@classmethod
+	def IsHost(cls, platformpattern):
+		""" Does the parameter match the name of the
+		    platform that we're executing on? """
+		ppre = re.compile(platformpattern, re.I)
+		if ppre.match(cls.hostplatform):
+			return True
+		return False
+
+
+# Make sure not to start up on an unsupported platform
+if not HostPlatform.IsKnown(HostPlatform.hostplatform):
+	raise Exception("raptor_data module loaded on an unrecognised platform '%s'. Expected one of %s" % (HostPlatform.hostplatform, str(HostPlatform.hostplatforms)))
+
+
+# raptor_data module classes
+
+class Model(object):
+	"Base class for data-model objects"
+
+	__slots__ = ('host', 'source', 'cacheID')
+
+	def __init__(self):
+		self.source = None	# XML file
+		self.host = None
+		self.cacheID = ""	# default set of cached objects
+		# not using the cache parameter - there to make the 
+		# init for all Model objects "standard"
+
+
+	def SetSourceFile(self, filename):
+		self.source = filename
+
+
+	def SetProperty(self, name, value):
+		raise InvalidPropertyError()
+
+
+	def AddChild(self, child):
+		raise InvalidChildError()
+
+
+	def Valid(self):
+		return False
+
+	def IsApplicable(self):
+		"This variant may be caused to only apply when used on a particular host build platform"
+		if self.host is None:
+			return True
+
+		if HostPlatform.IsHost(self.host):
+			return True
+
+		return False
+
+
+class InvalidPropertyError(Exception):
+	pass
+
+class InvalidChildError(Exception):
+	pass
+
+class BadReferenceError(Exception):
+	pass
+
+
+class Reference(Model):
+	"Base class for data-model reference objects"
+
+	def __init__(self, ref = None):
+		Model.__init__(self)
+		self.ref = ref
+		self.modifiers = []
+
+	def SetProperty(self, name, value):
+		if name == "ref":
+			self.ref = value
+		elif name == "mod":
+			self.modifiers = value.split(".")
+		else:
+			raise InvalidPropertyError()
+
+	def Resolve(self):
+		raise BadReferenceError()
+
+	def GetModifiers(self, cache):
+		mods = []
+		for m in self.modifiers:
+			try:
+				mods.append(cache.FindNamedVariant(m))
+			except KeyError:
+				raise BadReferenceError(m)
+		return mods
+
+	def Valid(self):
+		return self.ref
+
+
+class VariantContainer(Model):
+
+	def __init__(self):
+		Model.__init__(self)	# base class constructor
+		self.variants = []
+
+
+	def __str__(self):
+		return "\n".join([str(v) for v in self.variants])
+
+
+	def AddVariant(self, variant):
+		if type(variant) is types.StringTypes:
+			variant = VariantRef(ref = variant)
+
+
+		# Only add the variant if it's not in the list
+		# already
+		if not variant in self.variants:
+			self.variants.append(variant)
+
+	def GetVariants(self, cache):
+		# resolve any VariantRef objects into Variant objects
+		missing_variants = []
+		for i,var in enumerate(self.variants):
+			if isinstance(var, Reference):
+				try:
+					self.variants[i] = var.Resolve(cache=cache)
+
+				except BadReferenceError:
+					missing_variants.append(var.ref)
+
+		if len(missing_variants) > 0:
+			raise MissingVariantException("Missing variants '%s'", " ".join(missing_variants))
+
+		return self.variants
+
+
+class Interface(Model):
+
+	def __init__(self, name = None):
+		Model.__init__(self)	# base class constructor
+		self.name = name
+		self.flm = None
+		self.abstract = False
+		self.extends = None
+		self.params = []
+		self.paramgroups = []
+
+	def __str__(self):
+		return "<interface name='%s'>" % self.name + "</interface>"
+
+	def FindParent(self, cache):
+		try:
+			return cache.FindNamedInterface(self.extends, self.cacheID)
+		except KeyError:
+			raise BadReferenceError("Cannot extend interface because it cannot be found: "+str(self.extends))
+
+	def GetParams(self, cache):
+		if self.extends != None:
+			parent = self.FindParent(cache)
+
+			# what parameter names do we have already?
+			names = set([x.name for x in self.params])
+
+			# pick up ones we don't have that are in our parent
+			pp = []
+			for p in parent.GetParams(cache):
+				if not p.name in names:
+					pp.append(p)
+
+			# list parent parameters first then ours
+			pp.extend(self.params)
+			return pp
+
+		return self.params
+
+	def GetParamGroups(self, cache):
+		if self.extends != None:
+			parent = self.FindParent(cache)
+
+			# what parameter names do we have already?
+			patterns = set([x.pattern for x in self.paramgroups])
+
+			# pick up ones we don't have that are in our parent
+			for g in parent.GetParamGroups(cache):
+				if not g.pattern in patterns:
+					self.paramgroups.append(g)
+
+		return self.paramgroups
+
+
+	def GetFLMIncludePath(self, cache):
+		"absolute path to the FLM"
+
+		if self.flm == None:
+			if self.extends != None:
+				parent = self.FindParent(cache)
+
+				return parent.GetFLMIncludePath(cache)
+			else:
+				raise InvalidPropertyError()
+
+		if not os.path.isabs(self.flm):
+			self.flm = os.path.join(os.path.dirname(self.source), self.flm)
+
+		return generic_path.Path(self.flm)
+
+
+	def SetProperty(self, name, value):
+		if name == "name":
+			self.name = value
+		elif name == "flm":
+			self.flm = value
+		elif name == "abstract":
+			self.abstract = (value == "true")
+		elif name == "extends":
+			self.extends = value
+		else:
+			raise InvalidPropertyError()
+
+
+	def AddChild(self, child):
+		if isinstance(child, Parameter):
+			self.AddParameter(child)
+		elif isinstance(child, ParameterGroup):
+			self.AddParameterGroup(child)
+		else:
+			raise InvalidChildError()
+
+
+	def AddParameter(self, parameter):
+		self.params.append(parameter)
+
+	def AddParameterGroup(self, parametergroup):
+		self.paramgroups.append(parametergroup)
+
+	def Valid(self):
+		return (self.name != None)
+
+
+class InterfaceRef(Reference):
+
+	def __str__(self):
+		return "<interfaceRef ref='%s'/>" % self.ref
+
+	def Resolve(self, cache):
+		try:
+			return cache.FindNamedInterface(self.ref, self.cacheID)
+		except KeyError:
+			raise BadReferenceError()
+
+
+class Specification(VariantContainer):
+
+	def __init__(self, name = "", type = ""):
+		VariantContainer.__init__(self)	# base class constructor
+		self.name = name
+		self.type = type
+		self.interface = None
+		self.childSpecs = []
+		self.parentSpec = None
+
+
+	def __str__(self):
+		s = "<spec name='%s'>" % str(self.name)
+		s += VariantContainer.__str__(self)
+		for c in self.childSpecs:
+			s += str(c) + '\n'
+		s += "</spec>"
+		return s
+
+
+	def SetProperty(self, name, value):
+		if name == "name":
+			self.name = value
+		else:
+			raise InvalidPropertyError()
+
+
+	def Configure(self, config, cache):
+		# configure all the children (some may be Filters or parents of)
+		for spec in self.GetChildSpecs():
+			spec.Configure(config, cache = cache)
+
+
+	def HasInterface(self):
+		return self.interface != None
+
+
+	def SetInterface(self, interface):
+		if isinstance(interface, Interface) \
+		or isinstance(interface, InterfaceRef):
+			self.interface = interface
+		else:
+			self.interface = InterfaceRef(ref = interface)
+
+
+	def GetInterface(self, cache):
+		"""return the Interface (fetching from the cache if it was a ref)
+		may return None"""
+
+		if self.interface == None \
+		or isinstance(self.interface, Interface):
+			return self.interface
+
+		if isinstance(self.interface, InterfaceRef):
+			try:
+				self.interface = self.interface.Resolve(cache=cache)
+				return self.interface
+
+			except BadReferenceError:
+				raise MissingInterfaceError("Missing interface %s" % self.interface.ref)
+
+	def AddChild(self, child):
+		if isinstance(child, Specification):
+			self.AddChildSpecification(child)
+		elif isinstance(child, Interface) \
+		  or isinstance(child, InterfaceRef):
+			self.SetInterface(child)
+		elif isinstance(child, Variant) \
+		  or isinstance(child, VariantRef):
+			self.AddVariant(child)
+		else:
+			raise InvalidChildError()
+
+
+	def AddChildSpecification(self, child):
+		child.SetParentSpec(self)
+		self.childSpecs.append(child)
+
+
+	def SetParentSpec(self, parent):
+		self.parentSpec = parent
+
+
+	def GetChildSpecs(self):
+		return self.childSpecs
+
+
+	def Valid(self):
+		return True
+
+
+	def GetAllVariantsRecursively(self, cache):
+		"""Returns all variants contained in this node and in its ancestors.
+
+		The returned value is a list, the structure of which is [variants-in-parent,
+		variants-in-self].
+
+		Note that the function recurses through parent *Specifications*, not through
+		the variants themselves.
+		"""
+		if self.parentSpec:
+			variants = self.parentSpec.GetAllVariantsRecursively(cache = cache)
+		else:
+			variants = []
+
+		variants.extend( self.GetVariants(cache = cache) )
+
+		return variants
+
+
+class Filter(Specification):
+	"""A Filter is two Specification nodes and a True/False switch.
+
+	Filter extends Specification to have two nodes, only one of
+	which can be active at any time. Which node is active is determined
+	when the Configure method is called after setting up a Condition.
+
+	If several Conditions are set, the test is an OR of all of them."""
+
+	def __init__(self, name = ""):
+		Specification.__init__(self, name = name)	# base class constructor
+		self.Else = Specification(name = name)     # same for Else part
+		self.isTrue = True
+		self.configNames = set()            #
+		self.variableNames = set()          # TO DO: Condition class
+		self.variableValues = {}            #
+
+	def __str__(self, prefix = ""):
+		s = "<filter name='%s'>\n"% self.name
+		s += "<if config='%s'>\n" % " | ".join(self.configNames)
+		s += Specification.__str__(self)
+		s += "</if>\n <else>\n"
+		s += str(self.Else)
+		s += " </else>\n</filter>\n"
+		return s
+
+
+	def SetConfigCondition(self, configName):
+		self.configNames = set([configName])
+
+	def AddConfigCondition(self, configName):
+		self.configNames.add(configName)
+
+
+	def SetVariableCondition(self, variableName, variableValues):
+		self.variableNames = set([variableName])
+		if type(variableValues) == types.ListType:
+			self.variableValues[variableName] = set(variableValues)
+		else:
+			self.variableValues[variableName] = set([variableValues])
+
+	def AddVariableCondition(self, variableName, variableValues):
+		self.variableNames.add(variableName)
+		if type(variableValues) == types.ListType:
+			self.variableValues[variableName] = set(variableValues)
+		else:
+			self.variableValues[variableName] = set([variableValues])
+
+
+	def Configure(self, buildUnit, cache):
+		self.isTrue = False
+
+		if buildUnit.name in self.configNames:
+			self.isTrue = True
+		elif self.variableNames:
+
+			evaluator = Evaluator(self.parentSpec, buildUnit, cache=cache)
+
+			for variableName in self.variableNames:
+				variableValue = evaluator.Get(variableName)
+
+				if variableValue in self.variableValues[variableName]:
+					self.isTrue = True
+					break
+
+		# configure all the children too
+		for spec in self.GetChildSpecs():
+			spec.Configure(buildUnit, cache=cache)
+
+
+	def HasInterface(self):
+		if self.isTrue:
+			return Specification.HasInterface(self)
+		else:
+			return self.Else.HasInterface()
+
+
+	def GetInterface(self, cache):
+		if self.isTrue:
+			return Specification.GetInterface(self, cache = cache)
+		else:
+			return self.Else.GetInterface(cache = cache)
+
+
+	def GetVariants(self, cache):
+		if self.isTrue:
+			return Specification.GetVariants(self, cache = cache)
+		else:
+			return self.Else.GetVariants(cache = cache)
+
+
+	def SetParentSpec(self, parent):
+		# base class method
+		Specification.SetParentSpec(self, parent)
+		# same for Else part
+		self.Else.SetParentSpec(parent)
+
+
+	def GetChildSpecs(self):
+		if self.isTrue:
+			return Specification.GetChildSpecs(self)
+		else:
+			return self.Else.GetChildSpecs()
+
+
+class Parameter(Model):
+
+	def __init__(self, name = None, default = None):
+		Model.__init__(self)	# base class constructor
+		self.name = name
+		self.default = default
+
+
+	def SetProperty(self, name, value):
+		if name == "name":
+			self.name = value
+		elif name == "default":
+			self.default = value
+		else:
+			raise InvalidPropertyError()
+
+
+	def Valid(self):
+		return (self.name != None)
+
+class ParameterGroup(Model):
+	"""A group of Parameters specified in an interface by a regexp"""
+	def __init__(self, pattern = None, default = None):
+		Model.__init__(self)	# base class constructor
+		self.pattern = pattern
+
+		self.patternre = None
+		if pattern:
+			try:
+				self.patternre = re.compile(pattern)
+			except TypeError:
+				pass
+		self.default = default
+
+
+	def SetProperty(self, pattern, value):
+		if pattern == "pattern":
+			self.pattern = value
+			self.patternre = re.compile(value)
+		elif pattern == "default":
+			self.default = value
+		else:
+			raise InvalidPropertyError()
+
+
+	def Valid(self):
+		return (self.pattern != None and self.patternre != None)
+
+
+class Operation(Model):
+	"Base class for variant operations"
+	__slots__ = 'type'
+	def __init__(self):
+		Model.__init__(self)	# base class constructor
+		self.type = None
+
+	def Apply(self, oldValue):
+		pass
+
+
+class Append(Operation):
+	__slots__ = ('name', 'value', 'separator')
+	def __init__(self, name = None, value = None, separator = " "):
+		Operation.__init__(self)	# base class constructor
+		self.name = name
+		self.value = value
+		self.separator = separator
+
+
+	def __str__(self):
+		attributes = "name='" + self.name + "' value='" + self.value + "' separator='" + self.separator + "'"
+		return "<append %s/>" % attributes
+
+
+	def Apply(self, oldValue):
+		if len(oldValue) > 0:
+			if len(self.value) > 0:
+				return oldValue + self.separator + self.value
+			else:
+				return oldValue
+		else:
+			return self.value
+
+
+	def SetProperty(self, name, value):
+		if name == "name":
+			self.name = value
+		elif name == "value":
+			self.value = value
+		elif name == "separator":
+			self.separator = value
+		else:
+			raise InvalidPropertyError()
+
+
+	def Valid(self):
+		return (self.name != None and self.value != None)
+
+
+class Prepend(Operation):
+	__slots__ = ('name', 'value', 'separator')
+	def __init__(self, name = None, value = None, separator = " "):
+		Operation.__init__(self)	# base class constructor
+		self.name = name
+		self.value = value
+		self.separator = separator
+
+
+	def __str__(self, prefix = ""):
+		attributes = "name='" + self.name + "' value='" + self.value + "' separator='" + self.separator + "'"
+		return "<prepend %s/>" % prefix
+
+
+	def Apply(self, oldValue):
+		if len(oldValue) > 0:
+			if len(self.value) > 0:
+				return self.value + self.separator + oldValue
+			else:
+				return oldValue
+		else:
+			return self.value
+
+
+	def SetProperty(self, name, value):
+		if name == "name":
+			self.name = value
+		elif name == "value":
+			self.value = value
+		elif name == "separator":
+			self.separator = value
+		else:
+			raise InvalidPropertyError()
+
+
+	def Valid(self):
+		return (self.name != None and self.value != None)
+
+
+class Set(Operation):
+	__slots__ = ('name', 'value', 'type', 'versionCommand', 'versionResult')
+	"""implementation of <set> operation"""
+
+	def __init__(self, name = None, value = "", type = ""):
+		Operation.__init__(self)	# base class constructor
+		self.name = name
+		self.value = value
+		self.type = type
+		self.versionCommand = ""
+		self.versionResult = ""
+
+
+	def __str__(self):
+		attributes = "name='" + self.name + "' value='" + self.value + "' type='" + self.type + "'"
+		if type == "tool":
+			attributes += " versionCommand='" + self.versionCommand + "' versionResult='" + self.versionResult
+
+		return "<set %s/>" % attributes
+
+
+	def Apply(self, oldValue):
+		return self.value
+
+
+	def SetProperty(self, name, value):
+		if name == "name":
+			self.name = value
+		elif name == "value":
+			self.value = value
+		elif name == "type":
+			self.type = value
+		elif name == "versionCommand":
+			self.versionCommand = value
+		elif name == "versionResult":
+			self.versionResult = value
+		elif name == "host":
+			if HostPlatform.IsKnown(value):
+				self.host = value
+		else:
+			raise InvalidPropertyError()
+
+
+	def Valid(self):
+		return (self.name != None and self.value != None)
+
+class BadToolValue(Exception):
+	pass
+
+class Env(Set):
+	"""implementation of <env> operator"""
+
+	def __init__(self, name = None, default = None, type = ""):
+		Set.__init__(self, name, "", type)	# base class constructor
+		self.default = default
+
+
+	def __str__(self):
+		attributes = "name='" + self.name + "' type='" + self.type + "'"
+		if self.default != None:
+			attributes += " default='" + self.default + "'"
+
+		if type == "tool":
+			attributes += " versionCommand='" + self.versionCommand + "' versionResult='" + self.versionResult + "'"
+
+		return "<env %s/>" % attributes
+
+
+	def Apply(self, oldValue):
+		try:
+			value = os.environ[self.name]
+			
+			if value:
+				if self.type in ["path", "tool", "toolchainpath"]:
+					# if this value is some sort of path or tool then we need to make sure
+					# it is a proper absolute path in our preferred format.
+					try:
+						path = generic_path.Path(value)
+						value = str(path.Absolute())
+					except ValueError,e:
+						raise BadToolValue("the environment variable %s is incorrect: %s" % (self.name, str(e)))
+					
+					if self.type in ["tool", "toolchainpath"]:
+						# if  we're dealing with tool-related values, then make sure that we can get "safe"
+						# versions if they contain spaces - if we can't, that's an error, as they won't
+						# survive full usage in the toolcheck or when used and/or referenced in FLMs						
+						if ' ' in value:
+							path = generic_path.Path(value)
+							spaceSafeValue = path.GetSpaceSafePath()
+						
+							if not spaceSafeValue:
+								raise BadToolValue("the environment variable %s is incorrect - it is a '%s' type but contains spaces that cannot be neutralised: %s" % (self.name, self.type, value))
+							
+							value = spaceSafeValue	
+				elif value.endswith('\\'):
+					# if this value ends in an un-escaped backslash, then it will be treated as a line continuation character
+					# in makefile parsing - un-escaped backslashes at the end of values are therefore escaped					
+					count = len(value) - len(value.rstrip('\\'))	# an odd number of backslashes means there's one to escape
+					if count % 2:
+						value += '\\'	
+		except KeyError:
+			if self.default != None:
+				value = self.default
+			else:
+				raise BadToolValue("%s is not set in the environment and has no default" % self.name)
+
+		return value
+
+
+	def SetProperty(self, name, value):
+		if name == "default":
+			self.default = value
+		else:
+			Set.SetProperty(self, name, value)
+
+
+	def Valid(self):
+		return (self.name != None)
+
+
+class BuildUnit(object):
+	"Represents an individual buildable unit."
+
+	def __init__(self, name, variants):
+		self.name = name
+		
+		# A list of Variant objects.
+		self.variants = variants
+
+		# Cache for the variant operations implied by this BuildUnit.
+		self.operations = []
+		self.variantKey = ""
+
+	def GetOperations(self, cache):
+		"""Return all operations related to this BuildUnit.
+		
+		The result is cached, and so will only be computed once per BuildUnit.
+		"""
+		key = '.'.join([x.name for x in self.variants])
+		if self.variantKey != key:
+			self.variantKey = key
+			for v in self.variants:
+				self.operations.extend( v.GetAllOperationsRecursively(cache=cache) )
+
+		return self.operations
+
+class Config(object):
+	"""Abstract type representing an argument to the '-c' option.
+
+	The fundamental property of a Config is that it can generate one or more
+	BuildUnits.
+	"""
+
+	def __init__(self):
+		self.modifiers = []
+
+	def AddModifier(self, variant):
+		self.modifiers.append(variant)
+
+	def ClearModifiers(self):
+		self.modifiers = []
+
+	def GenerateBuildUnits(self,cache):
+		"""Returns a list of BuildUnits.
+
+		This function must be overridden by derived classes.
+		"""
+		raise NotImplementedError()
+
+
+class Variant(Model, Config):
+
+	__slots__ = ('cache','name','type','host','extends','ops','variantRefs','allOperations')
+
+	def __init__(self, name = ""):
+		Model.__init__(self)
+		Config.__init__(self)
+		self.name = name
+		self.type = ""
+
+		# Operations defined inside this variant.
+		self.ops = []
+
+		# The name of our parent variant, if any.
+		self.extends = ""
+
+		# Any variant references used inside this variant.
+		self.variantRefs = []
+
+		self.allOperations = []
+
+	def SetProperty(self, name, value):
+		if name == "name":
+			self.name = value
+		elif name == "host":
+			if HostPlatform.IsKnown(value):
+				self.host = value
+		elif name == "extends":
+			self.extends = value
+		elif name == "type":
+			self.type = value
+		else:
+			raise InvalidPropertyError()
+
+	def AddChild(self, child):
+		if isinstance(child, Operation):
+			self.ops.append(child)
+		elif isinstance(child, VariantRef):
+			self.variantRefs.append(child)
+		else:
+			raise InvalidChildError()
+
+	def Valid(self):
+		return self.name
+
+	def AddOperation(self, op):
+		self.ops.append(op)
+
+	def GetAllOperationsRecursively(self, cache):
+		"""Returns a list of all operations in this variant.
+
+		The list elements are themselves lists; the overall structure of the
+		returned value is:
+
+		[ [ops-from-parent],[ops-from-varRefs], [ops-in-self] ]
+		"""
+
+		if not self.allOperations:
+			if self.extends:
+				parent = cache.FindNamedVariant(self.extends)
+				self.allOperations.extend( parent.GetAllOperationsRecursively(cache = cache) )
+			for r in self.variantRefs:
+				for v in [ r.Resolve(cache = cache) ] + r.GetModifiers(cache = cache):
+					self.allOperations.extend( v.GetAllOperationsRecursively(cache = cache) )
+			self.allOperations.append(self.ops)
+
+		return self.allOperations
+
+	def GenerateBuildUnits(self,cache):
+
+		name = self.name
+		vars = [self]
+
+		for m in self.modifiers:
+			name = name + "." + m.name
+			vars.append(m)
+		return [ BuildUnit(name=name, variants=vars) ]
+
+	def isDerivedFrom(self, progenitor, cache):
+		if self.name == progenitor:
+			return True
+
+		pname = self.extends
+		while pname is not None and pname is not '':
+			parent = cache.FindNamedVariant(pname)
+			if parent is None:
+				break
+			if parent.name == progenitor:
+				return True
+			pname = parent.extends
+
+		return False
+
+	def __str__(self):
+		s = "<var name='%s' extends='%s'>\n" % (self.name, self.extends)
+		for op in self.ops:
+			s +=  str(op) + '\n'
+		s += "</var>"
+		return s
+
+class VariantRef(Reference):
+
+	def __init__(self, ref=None):
+		Reference.__init__(self, ref = ref)
+
+	def __str__(self):
+		return "<varRef ref='%s'/>" % self.ref
+
+	def Resolve(self, cache):
+		try:
+			return cache.FindNamedVariant(self.ref)
+		except KeyError:
+			raise BadReferenceError(self.ref)
+
+class MissingVariantException(Exception):
+	pass
+
+class Alias(Model, Config):
+
+	def __init__(self, name=""):
+		Model.__init__(self)
+		Config.__init__(self)
+		self.name = name
+		self.meaning = ""
+		self.type = ""
+		self.varRefs = []
+		self.variants = []
+
+	def __str__(self):
+		return "<alias name='%s' meaning='%s'/>" % (self.name, self.meaning)
+
+	def SetProperty(self, key, val):
+		if key == "name":
+			self.name = val
+		elif key == "meaning":
+			self.meaning = val
+
+			for u in val.split("."):
+				self.varRefs.append( VariantRef(ref = u) )
+		elif key == "type":
+			self.type = val
+		else:
+			raise InvalidPropertyError()
+
+	def Valid(self):
+		return self.name and self.meaning
+
+	def Resolve(self, cache):
+		if not self.variants:
+			missing_variants = []
+			for r in self.varRefs:
+				try:
+					self.variants.append( r.Resolve(cache=cache) )
+				except BadReferenceError:
+					missing_variants.append(r.ref)
+				
+			if len(missing_variants) > 0:
+				raise MissingVariantException("Missing variants '%s'" % " ".join(missing_variants))
+
+	def GenerateBuildUnits(self, cache):
+		self.Resolve(cache)
+
+		name = self.name
+
+		for v in self.modifiers:
+			name = name + "." + v.name
+
+		return [ BuildUnit(name=name, variants=self.variants + self.modifiers) ]
+
+	def isDerivedFrom(self, progenitor, cache):
+		self.Resolve(cache)
+		for v in self.variants:
+			if v.isDerivedFrom(progenitor,cache):
+				return True
+		return False
+
+class AliasRef(Reference):
+
+	def __init__(self, ref=None):
+		Reference.__init__(self, ref)
+
+	def __str__(self):
+		return "<aliasRef ref='%s'/>" % self.ref
+
+	def Resolve(self, cache):
+		try:
+			return cache.FindNamedAlias(self.ref)
+		except KeyError:
+			raise BadReferenceError(self.ref)
+
+
+class Group(Model, Config):
+	def __init__(self, name=""):
+		Model.__init__(self)
+		Config.__init__(self)
+		self.name = name
+		self.childRefs = []
+
+	def SetProperty(self, key, val):
+		if key == "name":
+			self.name = val
+		else:
+			raise InvalidPropertyError()
+
+	def AddChild(self, child):
+		if isinstance( child, (VariantRef,AliasRef,GroupRef) ):
+			self.childRefs.append(child)
+		else:
+			raise InvalidChildError()
+
+	def Valid(self):
+		return self.name and self.childRefs
+
+	def __str__(self):
+		s = "<group name='%s'>" % self.name
+		for r in self.childRefs:
+			s += str(r)
+		s += "</group>"
+		return s
+
+	def GenerateBuildUnits(self, cache):
+		units = []
+		
+		missing_variants = []
+		for r in self.childRefs:
+			try:
+				obj = r.Resolve(cache=cache)
+			except BadReferenceError:
+				missing_variants.append(r.ref)
+			else:
+				obj.ClearModifiers()
+				try:
+					refMods = r.GetModifiers(cache)
+				except BadReferenceError,e:
+					missing_variants.append(str(e))
+				else:
+					for m in refMods + self.modifiers:
+						obj.AddModifier(m)
+
+					units.extend( obj.GenerateBuildUnits(cache) )
+
+		if len(missing_variants) > 0:
+			raise MissingVariantException("Missing variants '%s'" % " ".join(missing_variants))
+
+		return units
+
+
+class GroupRef(Reference):
+
+	def __init__(self, ref=None):
+		Reference.__init__(self, ref)
+
+	def __str__(self):
+		return "<groupRef ref='%s' mod='%s'/>" % (self.ref, ".".join(self.modifiers))
+
+	def Resolve(self, cache):
+		try:
+			return cache.FindNamedGroup(self.ref)
+		except KeyError:
+			raise BadReferenceError(self.ref)
+
+def GetBuildUnits(configNames, cache, logger):
+	"""expand a list of config strings like "arm.v5.urel" into a list
+	of BuildUnit objects that can be queried for settings.
+	
+	The expansion tries to be tolerant of errors in the XML so that a
+	typo in one part of a group does not invalidate the whole group.
+	"""
+	
+	# turn dot-separated name strings into Model objects (Group, Alias, Variant)
+	models = []
+		
+	for c in set(configNames):
+		ok = True
+		names = c.split(".")
+
+		base = names[0]
+		mods = names[1:]
+
+		if base in cache.groups:
+			x = cache.FindNamedGroup(base)
+		elif base in cache.aliases:
+			x = cache.FindNamedAlias(base)
+		elif base in cache.variants:
+			x = cache.FindNamedVariant(base)
+		else:
+			logger.Error("Unknown build configuration '%s'" % base)
+			continue
+
+		x.ClearModifiers()
+
+		for m in mods:
+			if m in cache.variants:
+				x.AddModifier( cache.FindNamedVariant(m) )
+			else:
+				logger.Error("Unknown build variant '%s'" % m)
+				ok = False
+				
+		if ok:
+			models.append(copy.copy(x))
+
+	# turn Model objects into BuildUnit objects
+	#
+	# all objects have a GenerateBuildUnits method but don't use
+	# that for Groups because it is not tolerant of errors (the
+	# first error raises an exception and the rest of the group is
+	# abandoned)
+	units = []
+		
+	while len(models) > 0:
+		x = models.pop()
+		try:
+			if isinstance(x, (Alias, Variant)):
+				# these we just turn straight into BuildUnits
+				units.extend(x.GenerateBuildUnits(cache))
+			elif isinstance(x, Group):
+				# deal with each part of the group separately (later)
+				for child in x.childRefs:
+					modChild = copy.copy(child)
+					modChild.modifiers = child.modifiers + [m.name for m in x.modifiers]
+					models.append(modChild)
+			elif isinstance(x, Reference):
+				# resolve references and their modifiers
+				try:
+					obj = x.Resolve(cache)
+					modObj = copy.copy(obj)
+					modObj.modifiers = x.GetModifiers(cache)
+				except BadReferenceError,e:
+					logger.Error("Unknown reference '%s'" % str(e))
+				else:
+					models.append(modObj)
+		except Exception, e:
+			logger.Error(str(e))
+
+	return units
+	
+class ToolErrorException(Exception):
+	def __init__(self, s):
+		Exception.__init__(self,s)
+
+class Tool(object):
+	"""Represents a tool that might be used by raptor e.g. a compiler"""
+
+	# It's difficult and expensive to give each tool a log reference but a class one
+	# will facilitate debugging when that is needed without being a design flaw the
+	# rest of the time.
+	log = raptor_utilities.nulllog
+
+	# For use in dealing with tools that return non-ascii version strings.
+	nonascii = ""
+	identity_chartable = chr(0)
+	for c in xrange(1,128):
+		identity_chartable += chr(c)
+	for c in xrange(128,256):
+		nonascii += chr(c)
+		identity_chartable += " "
+
+	def __init__(self, name, command, versioncommand, versionresult, id=""):
+		self.name = name
+		self.command = command
+		self.versioncommand = versioncommand
+		self.versionresult = versionresult
+		self.id = id # what config this is from - used in debug messages
+		self.date = None
+
+
+		# Assume the tool is unavailable or the wrong
+		# version until someone proves that it's OK
+		self.valid = False
+
+
+	def expand(self, toolset):
+		self.versioncommand = toolset.ExpandAll(self.versioncommand)
+		self.versionresult  = toolset.ExpandAll(self.versionresult)
+		self.command = toolset.ExpandAll(self.command)
+		self.key = hashlib.md5(self.versioncommand + self.versionresult).hexdigest()
+		
+		# We need the tool's date to find out if we should check it.
+		try:
+			if '/' in self.command:
+				testfile = os.path.abspath(self.command.strip("\"'"))
+			else:
+				# The tool isn't a relative or absolute path so the could be relying on the 
+				# $PATH variable to make it available.  We must find the tool if it's a simple 
+				# executable file (e.g. "armcc" rather than "python myscript.py") then get it's date. 
+				# We can use the date later to see if our cache is valid. 
+				# If it really is not a simple command then we won't be able to get a date and
+				# we won't be able to tell if it is altered or updated - too bad!
+				testfile = generic_path.Where(self.command)
+				#self.log.Debug("toolcheck: tool '%s' was found on the path at '%s' ", self.command, testfile)
+				if testfile is None:
+					raise Exception("Can't be found in path")
+
+			if not os.path.isfile(testfile):
+				raise Exception("tool %s appears to not be a file %s", self.command, testfile)
+				
+			testfile_stat = os.stat(testfile)
+			self.date = testfile_stat.st_mtime
+		except Exception,e:
+			# We really don't mind if the tool could not be dated - for any reason
+			Tool.log.Debug("toolcheck: '%s=%s' cannot be dated - this is ok, but the toolcheck won't be able to tell when a new version of the tool is installed. (%s)", self.name, self.command, str(e))
+			pass
+	
+			
+	def check(self, shell, evaluator, log = raptor_utilities.nulllog):
+
+		self.vre = re.compile(self.versionresult)
+
+		try:
+			self.log.Debug("Pre toolcheck: '%s' for version '%s'", self.name, self.versionresult)
+			p = subprocess.Popen(args=[shell, "-c", self.versioncommand], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+			log.Debug("Checking tool '%s' for version '%s'", self.name, self.versionresult)
+			versionoutput,err = p.communicate()
+		except Exception,e:
+			versionoutput=None
+
+		# Some tools return version strings with unicode characters! 
+		# There is no good response other than a lot of decoding and encoding.
+		# Simpler to ignore it:
+		versionoutput_a = versionoutput.translate(Tool.identity_chartable,"")
+
+		if versionoutput_a and self.vre.search(versionoutput_a) != None:
+			log.Debug("tool '%s' returned an acceptable version '%s'", self.name, versionoutput_a)
+			self.valid = True
+		else:
+			self.valid = False
+			raise ToolErrorException("tool '%s' from config '%s' did not return version '%s' as required.\nCommand '%s' returned:\n%s\nCheck your environment and configuration.\n" % (self.name, self.id, self.versionresult, self.versioncommand, versionoutput_a))
+
+def envhash(irrelevant_vars):
+	"""Determine something unique about this environment to identify it.
+	must ignore variables that change without mattering to the caller
+	e.g. perhaps PATH matters but PWD and PPID don't"""
+	envid = hashlib.md5()
+	for k in os.environ:
+		if k not in irrelevant_vars:
+			envid.update(os.environ[k])
+	return envid.hexdigest()[:16]
+
+
+class ToolSet(object):
+	""" 
+	This class manages a bunch of tools and keeps a cache of
+	all tools that it ever sees (across all configurations).
+	toolset.check() is called for each config but the cache is kept across calls to
+	catch the use of one tool in many configs.
+	write() is used to flush the cache to disc.
+	"""
+	# The raptor shell - this is not mutable.
+	if 'SBS_SHELL' in os.environ:
+		shell = os.environ['SBS_SHELL']
+	else:
+		hostbinaries = os.path.join(os.environ['SBS_HOME'], 
+	                                os.environ['HOSTPLATFORM_DIR'])
+	                            
+		if HostPlatform.IsHost('lin*'):
+			shell=os.path.join(hostbinaries, 'bin/bash')
+		else:
+			if 'SBS_CYGWIN' in os.environ:
+				shell=os.path.join(os.environ['SBS_CYGWIN'], 'bin\\bash.exe')
+			else:
+				shell=os.path.join(hostbinaries, 'cygwin\\bin\\bash.exe')
+
+
+	irrelevant_vars = ['PWD','OLDPWD','PID','PPID', 'SHLVL' ]
+
+
+	shell_version=".*GNU bash, version [34].*"
+	shell_re = re.compile(shell_version)
+	if 'SBS_BUILD_DIR' in os.environ:
+		cachefile_basename = str(generic_path.Join(os.environ['SBS_BUILD_DIR'],"toolcheck_cache_"))
+	elif 'EPOCROOT' in os.environ:
+		cachefile_basename = str(generic_path.Join(os.environ['EPOCROOT'],"epoc32/build/toolcheck_cache_"))
+	else:
+		cachefile_basename = None
+
+	tool_env_id = envhash(irrelevant_vars)
+	filemarker = "sbs_toolcache_2.8.2"
+
+	def __init__(self, log = raptor_utilities.nulllog, forced=False):
+		self.__toolcheckcache = {}
+
+		self.valid = True
+		self.checked = False
+		self.shellok = False
+		self.configname=""
+		self.cache_loaded = False
+		self.forced = forced
+
+		self.log=log
+
+		# Read in the tool cache
+		#
+		# The cache format is a hash key which identifies the
+		# command and the version that we're checking for. Then
+		# there are name,value pairs that record, e.g. the date
+		# of the command file or the name of the variable that
+		# the config uses for the tool (GNUCP or MWCC or whatever)
+
+		if ToolSet.cachefile_basename:
+			self.cachefilename = ToolSet.cachefile_basename+".tmp"
+			if not self.forced:
+				try:
+					f = open(self.cachefilename, "r+")
+					# if this tool cache was recorded in
+					# a different environment then ignore it.
+					marker = f.readline().rstrip("\r\n")
+					if marker == ToolSet.filemarker:
+						env_id_tmp = f.readline().rstrip("\r\n")
+						if env_id_tmp == ToolSet.tool_env_id:
+							try:
+								for l in f.readlines():
+									toolhistory  = l.rstrip(",\n\r").split(",")
+									ce = {}
+									for i in toolhistory[1:]:
+										(name,val) = i.split("=")
+										if name == "valid":
+											val = bool(val)
+										elif name == "age":
+											val = int(val)
+										elif name == "date":
+											if val != "None":
+												val = float(val)
+											else:
+												val= None
+
+										ce[name] = val
+									self.__toolcheckcache[toolhistory[0]] = ce
+								log.Info("Loaded toolcheck cache: %s\n", self.cachefilename)
+							except Exception, e:
+								log.Info("Ignoring garbled toolcheck cache: %s (%s)\n", self.cachefilename, str(e))
+								self.__toolcheckcache = {}
+									
+						else:
+							log.Info("Toolcheck cache %s ignored - environment changed\n", self.cachefilename)
+					else:
+						log.Info("Toolcheck cache not loaded = marker missing: %s %s\n", self.cachefilename, ToolSet.filemarker)
+					f.close()
+				except IOError, e:
+					log.Info("Failed to load toolcheck cache: %s\n", self.cachefilename)
+		else:
+			log.Debug("Toolcheck cachefile not created because EPOCROOT not set in environment.\n")
+
+	def check_shell(self):
+		# The command shell is a critical tool because all the other tools run
+		# within it so we must check for it first. It has to be in the path.
+		# bash 4 is preferred, 3 is accepted
+		try:
+			p = subprocess.Popen(args=[ToolSet.shell, '--version'], bufsize=1024, shell = False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
+			shellversion_out, errtxt = p.communicate()
+			if ToolSet.shell_re.search(shellversion_out) == None:
+				self.log.Error("A critical tool, '%s', did not return the required version '%s':\n%s\nPlease check that '%s' is in the path.", ToolSet.shell, ToolSet.shell_version, shellversion_out, ToolSet.shell)
+				self.valid = False
+		except Exception,e:
+			self.log.Error("A critical tool could not be found.\nPlease check that '%s' is in the path. (%s)", ToolSet.shell,  str(e))
+			self.valid = False
+
+		return self.valid
+
+	def check(self, evaluator, configname):
+		"""Check the toolset for a particular config"""
+
+		self.checked = True # remember that we did check something
+
+		if not self.shellok:
+			self.shellok = self.check_shell()
+		self.shellok = True
+
+		self.valid = self.valid and self.shellok
+
+		cache = self.__toolcheckcache 
+		for tool in evaluator.tools:
+			if not self.forced:
+				try:
+					t = cache[tool.key]
+						
+				except KeyError,e:
+					pass
+				else:
+					# if the cache has an entry for the tool then see if the date on
+					# the tool has changed (assuming the tool is a simple executable file)
+					if t.has_key('date') and (tool.date is None or (tool.date - t['date'] > 0.1))  :
+						self.log.Debug("toolcheck forced: '%s'  changed since the last check: %s < %s", tool.command, str(t['date']), str(tool.date))
+					else:
+						t['age'] = 0 # we used it so it's obviously needed
+						self.valid = self.valid and t['valid']
+						self.log.Debug("toolcheck saved on: '%s'", tool.name)
+						continue
+
+
+			self.log.Debug("toolcheck done: %s -key: %s" % (tool.name, tool.key))
+
+			try:
+				tool.check(ToolSet.shell, evaluator, log = self.log)
+			except ToolErrorException, e:
+				self.valid = False
+				self.log.Error("%s\n" % str(e))
+
+			# Tool failures are cached just like successes - don't want to repeat them
+			cache[tool.key] =  { "name" : tool.name, "valid" : tool.valid, "age" : 0 , "date" : tool.date }
+
+
+	def write(self):
+		"""Writes the tool check cache to disc.
+
+		   toolset.write()
+		"""
+		cache = self.__toolcheckcache 
+
+		# Write out the cache.
+		if self.checked and ToolSet.cachefile_basename:
+			self.log.Debug("Saving toolcache: %s", self.cachefilename)
+			try:
+				f = open(self.cachefilename, "w+")
+				f.write(ToolSet.filemarker+"\n")
+				f.write(ToolSet.tool_env_id+"\n")
+				for k,ce in cache.iteritems():
+
+					# If a tool has not been used for an extraordinarily long time
+					# then forget it - to prevent the cache from clogging up with old tools.
+					# Only write entries for tools that were found to be ok - so that the 
+					# next time the ones that weren't will be re-tested
+
+					if ce['valid'] and ce['age'] < 100:
+						ce['age'] += 1
+						f.write("%s," % k)
+						for n,v in ce.iteritems():
+							f.write("%s=%s," % (n,str(v)))
+					f.write("\n")
+				f.close()
+				self.log.Info("Created/Updated toolcheck cache: %s\n", self.cachefilename)
+			except Exception, e:
+				self.log.Info("Could not write toolcheck cache: %s", str(e))
+		return self.valid
+
+class UninitialisedVariableException(Exception):
+	pass
+
+class RecursionException(Exception):
+	pass
+
+class Evaluator(object):
+	"""Determine the values of variables under different Configurations.
+	Either of specification and buildUnit may be None."""
+
+
+	refRegex = re.compile("\$\((.+?)\)")
+
+	def __init__(self, specification, buildUnit, cache, gathertools = False):
+		self.dict = {}
+		self.tools = []
+		self.gathertools = gathertools
+		self.cache = cache
+
+		specName = "none"
+		configName = "none"
+
+		# A list of lists of operations.
+		opsLists = []
+
+		if buildUnit:
+			ol = buildUnit.GetOperations(cache)
+			self.buildUnit = buildUnit
+			
+			opsLists.extend( ol )
+
+		if specification:
+			for v in specification.GetAllVariantsRecursively(cache):
+				opsLists.extend( v.GetAllOperationsRecursively(cache) )
+
+		tools = {}
+
+		unfound_values = []
+		for opsList in opsLists:
+			for op in opsList:
+				# applying an Operation to a non-existent variable
+				# is OK. We assume that it is just an empty string.
+				try:
+					oldValue = self.dict[op.name]
+				except KeyError:
+					oldValue = ""
+
+				try:
+					newValue = op.Apply(oldValue)
+				except BadToolValue, e:
+					unfound_values.append(str(e))
+					newValue = "NO_VALUE_FOR_" + op.name
+					
+				self.dict[op.name] = newValue
+			
+				if self.gathertools:
+					if op.type == "tool" and op.versionCommand and op.versionResult:
+						tools[op.name] = Tool(op.name, newValue, op.versionCommand, op.versionResult, configName)
+
+		if len(unfound_values) > 0:
+			raise UninitialisedVariableException("\n".join(unfound_values))
+
+		if self.gathertools:
+			self.tools = tools.values()
+		else:
+			self.tools=[]
+
+		# resolve inter-variable references in the dictionary
+		unresolved = True
+
+		for k, v in self.dict.items():
+			self.dict[k] = v.replace("$$","__RAPTOR_ESCAPED_DOLLAR__")
+
+		while unresolved:
+			unresolved = False
+			for k, v in self.dict.items():
+				if v.find('$(' + k + ')') != -1:
+						raise RecursionException("Recursion Detected in variable '%s' in configuration '%s' " % (k,configName))
+				else:
+					expanded = self.ExpandAll(v, specName, configName)
+
+				if expanded != v:				# something changed?
+					self.dict[k] = expanded
+					unresolved = True			# maybe more to do
+
+		# unquote double-dollar references
+		for k, v in self.dict.items():
+			self.dict[k] = v.replace("__RAPTOR_ESCAPED_DOLLAR__","$")
+
+		for t in self.tools:
+			t.expand(self)
+
+
+
+	def Get(self, name):
+		"""return the value of variable 'name' or None if not found."""
+
+		if name in self.dict:
+			return self.dict[name]
+		else:
+			return None
+
+
+	def Resolve(self, name):
+		"""same as Get except that env variables are expanded.
+
+		raises BadReferenceError if the variable 'name' exists but a
+		contained environment variable does not exist."""
+		return self.Get(name) # all variables are now expanded anyway
+
+
+	def ResolveMatching(self, pattern):
+		""" Return a dictionary of all variables that match the pattern """
+		for k,v in self.dict.iteritems():
+			if pattern.match(k):
+				yield (k,v)
+
+
+	def ExpandAll(self, value, spec = "none", config = "none"):
+		"""replace all $(SOMETHING) in the string value.
+
+		returns the newly expanded string."""
+
+		refs = Evaluator.refRegex.findall(value)
+
+		# store up all the unset variables before raising an exception
+		# to allow us to find them all
+		unset_variables = [] 
+
+		for r in set(refs):
+			expansion = None
+
+			if r in self.dict:
+				expansion = self.dict[r]
+			else:
+				# no expansion for $(r)
+				unset_variables.append("Unset variable '%s' used in spec '%s' with config '%s'" % (r, spec, config))
+			if expansion != None:
+				value = value.replace("$(" + r + ")", expansion)
+
+		if len(unset_variables) > 0: # raise them all
+			raise UninitialisedVariableException(". ".join(unset_variables))
+
+		return value
+
+
+# raptor_data module functions
+
+
+# end of the raptor_data module
--- a/sbsv2/raptor/python/raptor_make.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/raptor_make.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,563 +1,799 @@
-#
-# 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: 
-# raptor_make module
-# This module contains the classes that write and call Makefile wrappers.
-#
-
-import hashlib
-import os
-import random
-import raptor
-import raptor_data
-import raptor_utilities
-import raptor_version
-import re
-import subprocess
-import time
-from raptor_makefile import *
-
-# raptor_make module classes
-
-class MakeEngine(object):
-
-	def __init__(self, Raptor):
-		self.raptor = Raptor
-		self.valid = True
-		self.makefileset = None
-		self.descrambler = None
-		self.descrambler_started = False
-
-		engine = Raptor.makeEngine
-		
-		# look for an alias first as this gives end-users a chance to modify
-		# the shipped variant rather than completely replacing it.
-		if engine in Raptor.cache.aliases:
-			avar = Raptor.cache.FindNamedAlias(engine)
-		elif engine in Raptor.cache.variants:
-			avar = Raptor.cache.FindNamedVariant(engine)
-		else:
-			Raptor.Error("No settings found for build engine '%s'", engine)
-			return
-					
-		# find the variant and extract the values
-		try:
-			units = avar.GenerateBuildUnits()
-			evaluator = Raptor.GetEvaluator( None, units[0] , gathertools=True)
-
-			# shell
-			self.shellpath = evaluator.Get("DEFAULT_SHELL")
-			usetalon_s = evaluator.Get("USE_TALON") 
-			self.usetalon = usetalon_s is not None and usetalon_s != ""
-			self.talonshell = str(evaluator.Get("TALON_SHELL"))
-			self.talontimeout = str(evaluator.Get("TALON_TIMEOUT"))
-			self.talonretries = str(evaluator.Get("TALON_RETRIES"))
-
-			# commands
-			self.initCommand = evaluator.Get("initialise")
-			self.buildCommand = evaluator.Get("build")
-			self.shutdownCommand = evaluator.Get("shutdown")
-
-			# options
-			self.makefileOption = evaluator.Get("makefile")
-			self.keepGoingOption = evaluator.Get("keep_going")
-			self.jobsOption = evaluator.Get("jobs")
-			self.defaultMakeOptions = evaluator.Get("defaultoptions")
-
-			# buffering
-			self.scrambled = (evaluator.Get("scrambled") == "true")
-
-			# check tool versions
-			Raptor.CheckToolset(evaluator, avar.name)
-			
-			# default targets (can vary per-invocation)
-			self.defaultTargets = Raptor.defaultTargets
-
-			# work out how to split up makefiles
-			try:
-				selectorNames = [ x.strip() for x in evaluator.Get("selectors").split(',') if x.strip() != "" ]
-				self.selectors = []
-
-
-				if len(selectorNames) > 0:
-					for name in selectorNames:
-						pattern = evaluator.Get(name.strip() + ".selector.iface")
-						target = evaluator.Get(name.strip() + ".selector.target")
-						ignoretargets = evaluator.Get(name.strip() + ".selector.ignoretargets")
-						self.selectors.append(MakefileSelector(name,pattern,target,ignoretargets))
-			except KeyError:
-				Raptor.Error("%s.selector.iface, %s.selector.target not found in make engine configuration", name, name)
-				self.selectors = []
-
-		except KeyError:
-			Raptor.Error("Bad '%s' configuration found.", engine)
-			self.valid = False
-			return
-
-		# there must at least be a build command...
-		if not self.buildCommand:
-				Raptor.Error("No build command for '%s'", engine)
-				self.valid = False
-
-
-		if self.usetalon:
-			talon_settings="""
-TALON_SHELL:=%s
-TALON_TIMEOUT:=%s
-TALON_RECIPEATTRIBUTES:=\
- name='$$RECIPE'\
- target='$$TARGET'\
- host='$$HOSTNAME'\
- layer='$$COMPONENT_LAYER'\
- component='$$COMPONENT_NAME'\
- bldinf='$$COMPONENT_META' mmp='$$PROJECT_META'\
- config='$$SBS_CONFIGURATION' platform='$$PLATFORM'\
- phase='$$MAKEFILE_GROUP' source='$$SOURCE
-export TALON_RECIPEATTRIBUTES TALON_SHELL TALON_TIMEOUT
-USE_TALON:=%s
-
-""" % (self.talonshell, self.talontimeout, "1")
-		else:
-			talon_settings="""
-USE_TALON:=
-
-"""
-		
-
-		self.makefile_prologue = """
-# generated by %s %s
-
-HOSTPLATFORM:=%s
-HOSTPLATFORM_DIR:=%s
-OSTYPE:=%s
-FLMHOME:=%s
-SHELL:=%s
-
-%s
-
-include %s
-
-""" 		% (  raptor.name, raptor_version.Version(),
-			 " ".join(raptor.hostplatform),
-			 raptor.hostplatform_dir,
-			 self.raptor.filesystem,
-			 str(self.raptor.systemFLM),
-			 self.shellpath,
-			 talon_settings,
-			 self.raptor.systemFLM.Append('globals.mk') )
-
-
-		self.makefile_epilogue = """
-
-include %s
-
-""" 			% (self.raptor.systemFLM.Append('final.mk') )
-
-	def Write(self, toplevel, specs, configs):
-		"""Generate a set of makefiles, or one big Makefile."""
-
-		if not self.valid:
-			return
-
-		self.toplevel = toplevel
-
-		# create the top-level makefiles
-
-		try:
-			self.makefileset = MakefileSet(directory = str(toplevel.Dir()),
-										   selectors = self.selectors,
-										   filenamebase = str(toplevel.File()),
-										   prologue = self.makefile_prologue,
-										   epilogue = self.makefile_epilogue,
-										   defaulttargets = self.defaultTargets)
-
-			# are we pruning duplicates?
-			self.prune = self.raptor.pruneDuplicateMakefiles
-			self.hashes = set()
-
-			# are we writing one Makefile or lots?
-			self.many = not self.raptor.writeSingleMakefile
-
-			# add a makefile for each spec under each config
-			config_makefileset = self.makefileset
-
-			for c in configs:
-				if self.many:
-					config_makefileset = self.makefileset.createChild(c.name)
-
-				# make sure the config_wide spec item is put out first so that it
-				# can affect everything.
-				ordered_specs=[]
-				config_wide_spec = None
-				for s in specs:
-					if s.name == "config_wide":
-						config_wide_spec = s
-					else:
-						ordered_specs.append(s)
-
-				if config_wide_spec is not None:
-					config_wide_spec.Configure(c)
-					self.WriteConfiguredSpec(config_makefileset, config_wide_spec, c, True)
-
-				for s in ordered_specs:
-					s.Configure(c)
-					self.WriteConfiguredSpec(config_makefileset, s, c, False)
-
-			self.makefileset.close()
-		except Exception,e:
-			self.raptor.Error("Failed to write makefile '%s': %s" % (str(toplevel),str(e)))
-
-
-	def WriteConfiguredSpec(self, parentMakefileSet, spec, config, useAllInterfaces):
-		# ignore this spec if it is empty
-		hasInterface = spec.HasInterface()
-		childSpecs = spec.GetChildSpecs()
-
-		if not hasInterface and not childSpecs:
-			return
-
-		parameters = []
-		dupe = True
-		iface = None
-		guard = None
-		if hasInterface:
-			# find the Interface (it may be a ref)
-			iface = spec.GetInterface()
-
-			if iface == None:
-				self.raptor.Error("No interface for '%s'", spec.name)
-				return
-
-			if iface.abstract:
-				self.raptor.Error("Abstract interface '%s' for '%s'",
-								  iface.name, spec.name)
-				return
-
-			# we need to guard the FLM call with a hash based on all the
-			# parameter values so that duplicate calls cannot be made.
-			# So we need to find all the values before we can write
-			# anything out.
-			md5hash = hashlib.md5()
-			md5hash.update(iface.name)
-
-			# we need an Evaluator to get parameter values for this
-			# Specification in the context of this Configuration
-			evaluator = self.raptor.GetEvaluator(spec, config)
-
-			def addparam(k, value, default):
-				if value == None:
-					if p.default != None:
-						value = p.default
-					else:
-						self.raptor.Error("%s undefined for '%s'",
-										  k, spec.name)
-						value = ""
-
-				parameters.append((k, value))
-				md5hash.update(value)
-
-			# parameters required by the interface
-			for p in iface.GetParams():
-				val = evaluator.Resolve(p.name)
-				addparam(p.name,val,p.default)
-
-			# Use Patterns to fetch a group of parameters
-			for g in iface.GetParamGroups():
-				for k,v in evaluator.ResolveMatching(g.patternre):
-					addparam(k,v,g.default)
-
-			hash = md5hash.hexdigest()
-			dupe = hash in self.hashes
-
-			self.hashes.add(hash)
-
-		# we only create a Makefile if we have a new FLM call to contribute,
-		# OR we are not pruning duplicates (guarding instead)
-		# OR we have some child specs that need something to include them.
-		if dupe and self.prune and not childSpecs:
-			return
-
-		makefileset = parentMakefileSet
-		# Create a new layer of makefiles?
-		if self.many:
-			makefileset = makefileset.createChild(spec.name)
-
-		if not (self.prune and dupe):
-			if self.prune:
-				guard = ""
-			else:
-				guard = "guard_" + hash
-
-		# generate the call to the FLM
-		if iface is not None:
-			makefileset.addCall(spec.name, config.name, iface.name, useAllInterfaces, iface.GetFLMIncludePath(), parameters, guard)
-
-		# recursive includes
-
-		for child in childSpecs:
-			self.WriteConfiguredSpec(makefileset, child, config, useAllInterfaces)
-
-		if self.many:
-			makefileset.close() # close child set of makefiles as we'll never see them again.
-
-	def Make(self, makefileset):
-		"run the make command"
-
-		if not self.valid:
-			return False
-	
-		if self.usetalon:
-			# Always use Talon since it does the XML not
-			# just descrambling
-			if not self.StartTalon() and not self.raptor.keepGoing:
-				self.Tidy()
-				return False
-		else:
-			# use the descrambler if we are doing a parallel build on
-			# a make engine which does not buffer each agent's output
-			if self.raptor.jobs > 1 and self.scrambled:
-				self.StartDescrambler()
-				if  not self.descrambler_started and not self.raptor.keepGoing:
-					self.Tidy()
-					return False
-			
-		# run any initialisation script
-		if self.initCommand:
-			self.raptor.Info("Running %s", self.initCommand)
-			if os.system(self.initCommand) != 0:
-				self.raptor.Error("Failed in %s", self.initCommand)
-				self.Tidy()
-				return False
-
-		# Save file names to a list, to allow the order to be reversed
-		fileName_list = list(self.makefileset.makefileNames())
-
-		# Iterate through args passed to raptor, searching for CLEAN or REALLYCLEAN
-		clean_flag = False
-		for arg in self.raptor.args:
-			clean_flag = ("CLEAN" in self.raptor.args) or \
-			            ("REALLYCLEAN" in self.raptor.args)
-
-		# Files should be deleted in the opposite order to the order
-		# they were built. So reverse file order if cleaning
-		if clean_flag:
-			fileName_list.reverse()
-
-		# Process each file in turn
-		for makefile in fileName_list:
-			if not os.path.exists(makefile):
-				self.raptor.Info("Skipping makefile %s", makefile)
-				continue
-			self.raptor.Info("Making %s", makefile)
-			# assemble the build command line
-			command = self.buildCommand
-
-			if self.makefileOption:
-				command += " " + self.makefileOption + " " + '"' + str(makefile) + '"'
-
-			if self.raptor.keepGoing and self.keepGoingOption:
-				command += " " + self.keepGoingOption
-
-			if self.raptor.jobs > 1 and self.jobsOption:
-				command += " " + self.jobsOption +" "+ str(self.raptor.jobs)
-
-			# Set default options first so that they can be overridden by
-			# ones set by the --mo option on the raptor commandline:
-			command += " " + self.defaultMakeOptions
-			# Can supply options on the commandline to override default settings.
-			if len(self.raptor.makeOptions) > 0:
-				command += " " + " ".join(self.raptor.makeOptions)
-
-			# Switch off dependency file including?
-			if self.raptor.noDependInclude:
-				command += " NO_DEPEND_INCLUDE=1"
-			
-			if self.usetalon:
-				# use the descrambler if we set it up
-				command += ' TALON_DESCRAMBLE=' 
-				if self.scrambled:
-					command += '1 '
-				else:
-					command += '0 '
-			else:
-				if self.descrambler_started:
-					command += ' DESCRAMBLE="' + self.descrambler + '"'
-			
-			# use the retry mechanism if requested
-			if self.raptor.tries > 1:
-				command += ' RECIPETRIES=' + str(self.raptor.tries)
-				command += ' TALON_RETRIES=' + str(self.raptor.tries - 1)
-
-			# targets go at the end, if the makefile supports them
-			addTargets = self.raptor.targets[:]
-			ignoreTargets = self.makefileset.ignoreTargets(makefile)
-			if addTargets and ignoreTargets:
-				for target in self.raptor.targets:
-					if re.match(ignoreTargets, target):
-						addTargets.remove(target)
-
-			if addTargets:
-				command += " " + " ".join(addTargets)
-
-			self.raptor.Info("Executing '%s'", command)
-
-			# execute the build.
-			# the actual call differs between Windows and Unix.
-			# bufsize=1 means "line buffered"
-			#
-			try:
-				makeenv=os.environ.copy()
-				if self.usetalon:
-					makeenv['TALON_RECIPEATTRIBUTES']="none"
-					makeenv['TALON_SHELL']=self.talonshell
-					makeenv['TALON_BUILDID']=str(self.buildID)
-					makeenv['TALON_TIMEOUT']=str(self.talontimeout)
-				if self.raptor.filesystem == "unix":
-					p = subprocess.Popen(command, bufsize=65535,
-									     stdout=subprocess.PIPE,
-									     stderr=subprocess.STDOUT,
-									     close_fds=True, env=makeenv, shell=True)
-				else:
-					p = subprocess.Popen(command, bufsize=65535,
-									     stdout=subprocess.PIPE,
-									     stderr=subprocess.STDOUT,
-									     universal_newlines=True, env=makeenv)
-				stream = p.stdout
-
-
-				line = " "
-				while line:
-					line = stream.readline()
-					self.raptor.out.write(line)
-
-				# should be done now
-				returncode = p.wait()
-
-
-				if returncode != 0  and not self.raptor.keepGoing:
-					self.Tidy()
-					return False
-
-			except Exception,e:
-				self.raptor.Error("Exception '%s' during '%s'", str(e), command)
-				self.Tidy()
-				return False
-
-		# run any shutdown script
-		if self.shutdownCommand != None and self.shutdownCommand != "":
-			self.raptor.Info("Running %s", self.shutdownCommand)
-			if os.system(self.shutdownCommand) != 0:
-				self.raptor.Error("Failed in %s", self.shutdownCommand)
-				self.Tidy()
-				return False
-
-		self.Tidy()
-		return True
-
-	def Tidy(self):
-		if self.usetalon:
-			self.StopTalon() 
-		else:
-			"clean up after the make command"
-			self.StopDescrambler()
-
-	def StartTalon(self):
-		# the talon command
-		beginning = raptor.hostplatform_dir + "/bin"
-		if "win" in raptor.hostplatform:
-			end = ".exe"
-		else:
-			end = ""
-			
-		self.talonctl = str(self.raptor.home.Append(beginning, "talonctl"+end))
-			
-		# generate a unique build number
-		random.seed()
-		looking = True
-		tries = 0
-		while looking and tries < 100:
-			self.buildID = raptor.name + str(random.getrandbits(32))
-			
-			command = self.talonctl + " start"
-
-			os.environ["TALON_BUILDID"] = self.buildID
-			self.raptor.Info("Running %s", command)
-			looking = (os.system(command) != 0)
-			tries += 1
-		if looking:
-			self.raptor.Error("Failed to initilaise the talon shell for this build")
-			self.talonctl = ""
-			return False
-		
-		return True
-	
-	def StopTalon(self):
-		if self.talonctl:
-			command = self.talonctl + " stop"
-			self.talonctl = ""
-			
-			self.raptor.Info("Running %s", command)
-			if os.system(command) != 0:
-				self.raptor.Error("Failed in %s", command)
-				return False
-			
-		return True
-	
-	def StartDescrambler(self):
-		# the descrambler command
-		beginning = raptor.hostplatform_dir + "/bin"
-		if "win" in raptor.hostplatform:
-			end = ".exe"
-		else:
-			end = ""
-
-		self.descrambler = str(self.raptor.home.Append(beginning, "sbs_descramble"+end))
-			
-		# generate a unique build number
-		random.seed()
-		looking = True
-		tries = 0
-		while looking and tries < 100:
-			buildID = raptor.name + str(random.getrandbits(32))
-
-			command = self.descrambler + " " + buildID + " start"
-			self.raptor.Info("Running %s", command)
-			looking = (os.system(command) != 0)
-			tries += 1
-
-		if looking:
-			self.raptor.Error("Failed to start the log descrambler")
-			self.descrambler_started = True
-			return False
-
-		self.descrambler_started = True
-		self.descrambler +=	" " + buildID
-
-		return  True
-
-	def StopDescrambler(self):
-		if self.descrambler_started:
-			command = self.descrambler + " stop"
-			self.descrambler = ""
-
-			self.raptor.Info("Running %s", command)
-			if os.system(command) != 0:
-				self.raptor.Error("Failed in %s", command)
-				return False
-		return True
-
-# raptor_make module functions
-
-
-# end of the raptor_make module
+#
+# 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: 
+# raptor_make module
+# This module contains the classes that write and call Makefile wrappers.
+#
+
+import hashlib
+import os
+import random
+import raptor
+import raptor_timing
+import raptor_utilities
+import raptor_version
+import raptor_data
+import re
+import subprocess
+import time
+from raptor_makefile import *
+import traceback
+import sys
+from xml.sax.saxutils import escape
+from xml.sax.saxutils import unescape
+
+
+class BadMakeEngineException(Exception):
+	pass
+
+def string_following(prefix, str):
+	"""If str starts with prefix then return the rest of str, otherwise None"""
+	if str.startswith(prefix):
+		return str[len(prefix):]
+	else:
+		return None
+
+def XMLEscapeLog(stream):
+	""" A generator that reads a raptor log from a stream and performs an XML escape
+	    on all text between tags, which is usually make output that could contain
+	    illegal characters that upset XML-based log parsers.
+	    This function yields "xml-safe" output line by line.
+	"""
+	inRecipe = False
+
+	for line in stream:
+		if line.startswith("<recipe"):
+			inRecipe = True
+		elif line.startswith("</recipe"):
+			inRecipe = False
+			
+		# unless we are inside a "recipe", any line not starting
+		# with "<" is free text that must be escaped.
+		if inRecipe or line.startswith("<"):
+			yield line
+		else:
+			yield escape(line)
+
+def AnnoFileParseOutput(annofile):
+	""" A generator that extracts log output from an emake annotation file, 
+	    perform an XML-unescape on it and "yields" it line by line.  """
+	if isinstance(annofile,str):
+		af = open(annofile, "r")
+	else:
+		af = annofile
+
+	inOutput = False
+
+	buildid = ""
+	for line in af:
+		line = line.rstrip("\n\r")
+
+
+		if not inOutput:
+			o = string_following("<output>", line)
+			if not o:
+				o = string_following('<output src="prog">', line)
+
+			if o:
+				inOutput = True	
+				yield unescape(o)+'\n'
+				continue
+
+
+			o = string_following('<build id="',line)
+			if o:
+				buildid = o[:o.find('"')]
+				yield "Starting build: "+buildid+"\n"
+				continue 
+
+			o = string_following('<metric name="duration">', line)
+			if o:
+				secs = int(o[:o.find('<')])
+				if secs != 0:
+					duration = "%d:%d" % (secs/60, secs % 60)
+				else:
+					duration = "0:0"
+				continue 
+
+
+			o = string_following('<metric name="clusterAvailability">', line)
+			if o:
+				availability = o[:o.find('<')]
+				continue 
+				
+		else:
+			end_output = line.find("</output>")
+		
+			if end_output != -1:
+				line = line[:end_output]
+				inOutput = False
+			
+			if line != "":	
+				yield unescape(line)+'\n'
+
+	yield "Finished build: %s   Duration: %s (m:s)   Cluster availability: %s%%\n" %(buildid,duration,availability)
+	af.close()
+
+
+
+# raptor_make module classes
+
+class MakeEngine(object):
+
+	def __init__(self, Raptor, engine="make_engine"):
+		self.raptor = Raptor
+		self.valid = True
+		self.descrambler = None
+		self.descrambler_started = False
+
+		# look for an alias first as this gives end-users a chance to modify
+		# the shipped variant rather than completely replacing it.
+		if engine in Raptor.cache.aliases:
+			avar = Raptor.cache.FindNamedAlias(engine)
+		elif engine in Raptor.cache.variants:
+			avar = Raptor.cache.FindNamedVariant(engine)
+		else:
+			raise BadMakeEngineException("'%s' does not appear to be a make engine - no settings found for it" % engine)
+
+		if not avar.isDerivedFrom("make_engine", Raptor.cache):
+			raise BadMakeEngineException("'%s' is not a build engine (it's a variant but it does not extend 'make_engine')" % engine)
+					
+		# find the variant and extract the values
+		try:
+			units = avar.GenerateBuildUnits(Raptor.cache)
+			evaluator = Raptor.GetEvaluator( None, units[0] , gathertools=True)
+
+			# shell
+			self.shellpath = evaluator.Get("DEFAULT_SHELL")
+			usetalon_s = evaluator.Get("USE_TALON") 
+			self.usetalon = usetalon_s is not None and usetalon_s != ""
+			self.talonshell = str(evaluator.Get("TALON_SHELL"))
+			self.talontimeout = str(evaluator.Get("TALON_TIMEOUT"))
+			self.talonretries = str(evaluator.Get("TALON_RETRIES"))
+			
+			# work around for RVCT 2.2 failed compiles
+			delete_on_failed_compile_s = evaluator.Get("DELETE_ON_FAILED_COMPILE")
+			self.delete_on_failed_compile = ""
+			if delete_on_failed_compile_s is not None and delete_on_failed_compile_s != "":
+				self.delete_on_failed_compile = "1"
+
+			# commands
+			self.initCommand = evaluator.Get("initialise")
+			self.buildCommand = evaluator.Get("build")
+			self.shutdownCommand = evaluator.Get("shutdown")
+
+			# options
+			self.makefileOption = evaluator.Get("makefile")
+			self.keepGoingOption = evaluator.Get("keep_going")
+			self.jobsOption = evaluator.Get("jobs")
+			self.defaultMakeOptions = evaluator.Get("defaultoptions")
+
+			# Logging
+			#  copylogfromannofile means, for emake, that we should ignore 
+			# emake's console output and instead extract output from its annotation
+			# file.  This is a workaround for a problem where some emake
+			# console output is lost.  The annotation file has a copy of this
+			# output in the "parse" job and it turns out to be uncorrupted.
+			self.copyLogFromAnnoFile = (evaluator.Get("copylogfromannofile") == "true")
+			self.annoFileName = None
+
+			if self.copyLogFromAnnoFile:
+				for o in self.raptor.makeOptions:
+					self.annoFileName = string_following("--emake-annofile=", o)
+					if self.annoFileName:
+						self.raptor.Info("annofile: " + o)
+
+				if not self.annoFileName:
+					self.raptor.Info("Cannot copy log from annotation file as no annotation filename was specified via the option --mo=--emake-annofile=<filename>")
+					self.copyLogFromAnnoFile = False
+
+			# buffering
+			self.scrambled = (evaluator.Get("scrambled") == "true")
+
+			# check tool versions
+			Raptor.CheckToolset(evaluator, avar.name)
+			
+			# default targets (can vary per-invocation)
+			self.defaultTargets = Raptor.defaultTargets
+
+			# work out how to split up makefiles
+			try:
+				selectorNames = [ x.strip() for x in evaluator.Get("selectors").split(',') if x.strip() != "" ]
+				self.selectors = []
+
+
+				if len(selectorNames) > 0:
+					for name in selectorNames:
+						pattern = evaluator.Get(name.strip() + ".selector.iface")
+						target = evaluator.Get(name.strip() + ".selector.target")
+						ignoretargets = evaluator.Get(name.strip() + ".selector.ignoretargets")
+						self.selectors.append(MakefileSelector(name,pattern,target,ignoretargets))
+			except KeyError:
+				Raptor.Error("%s.selector.iface, %s.selector.target not found in make engine configuration", name, name)
+				self.selectors = []
+
+		except KeyError:
+			self.valid = False
+			raise BadMakeEngineException("Bad '%s' configuration found." % engine)
+
+		# there must at least be a build command...
+		if not self.buildCommand:
+			self.valid = False
+			raise BadMakeEngineException("No build command for '%s'"% engine)
+
+
+		if self.usetalon:
+			talon_settings="""
+TALON_SHELL:=%s
+TALON_TIMEOUT:=%s
+TALON_RECIPEATTRIBUTES:=\
+ name='$$RECIPE'\
+ target='$$TARGET'\
+ host='$$HOSTNAME'\
+ layer='$$COMPONENT_LAYER'\
+ component='$$COMPONENT_NAME'\
+ bldinf='$$COMPONENT_META' mmp='$$PROJECT_META'\
+ config='$$SBS_CONFIGURATION' platform='$$PLATFORM'\
+ phase='$$MAKEFILE_GROUP' source='$$SOURCE'
+export TALON_RECIPEATTRIBUTES TALON_SHELL TALON_TIMEOUT
+USE_TALON:=%s
+
+""" % (self.talonshell, self.talontimeout, "1")
+		else:
+			talon_settings="""
+USE_TALON:=
+
+"""
+
+
+		timing_start = "$(info " + \
+				raptor_timing.Timing.custom_string(tag = "start",
+				object_type = "makefile", task = "parse",
+				key = "$(THIS_FILENAME)",
+				time="$(shell date +%s.%N)").rstrip("\n") + ")"
+				
+		timing_end = "$(info " + \
+				raptor_timing.Timing.custom_string(tag = "end",
+				object_type = "makefile", task = "parse",
+				key = "$(THIS_FILENAME)",
+				time="$(shell date +%s.%N)").rstrip("\n") + ")"
+
+
+		self.makefile_prologue = """
+
+# generated by %s %s
+
+HOSTPLATFORM:=%s
+HOSTPLATFORM_DIR:=%s
+OSTYPE:=%s
+FLMHOME:=%s
+SHELL:=%s
+THIS_FILENAME:=$(firstword $(MAKEFILE_LIST))
+DELETE_ON_FAILED_COMPILE:=%s 
+
+%s
+
+include %s
+
+""" 		% (  raptor.name, raptor_version.fullversion(),
+			 " ".join(raptor.hostplatform),
+			 raptor.hostplatform_dir,
+			 self.raptor.filesystem,
+			 str(self.raptor.systemFLM),
+			 self.shellpath,
+			 self.delete_on_failed_compile,
+			 talon_settings,
+			 self.raptor.systemFLM.Append('globals.mk') )
+
+		# Unless dependency processing has been eschewed via the CLI, use a .DEFAULT target to
+		# trap missing dependencies (ignoring user config files that we know are usually absent)
+		if not (self.raptor.noDependGenerate or self.raptor.noDependInclude):
+			self.makefile_prologue += """
+
+$(FLMHOME)/user/final.mk:
+$(FLMHOME)/user/default.flm:
+$(FLMHOME)/user/globals.mk:
+
+.DEFAULT::
+	@echo "<warning>Missing dependency detected: $@</warning>"
+
+"""
+
+		# Only output timings if requested on CLI
+		if self.raptor.timing:
+			self.makefile_prologue += "\n# Print Start-time of Makefile parsing\n" \
+					+ timing_start + "\n\n"
+	
+	
+			self.makefile_epilogue = "\n\n# Print End-time of Makefile parsing\n" \
+				+ timing_end + "\n"
+		else:
+			self.makefile_epilogue = ""
+
+		self.makefile_epilogue += """
+
+include %s
+
+""" 			% (self.raptor.systemFLM.Append('final.mk') )
+
+	def Write(self, toplevel, specs, configs):
+		"""Generate a set of makefiles, or one big Makefile."""
+
+		if not self.valid:
+			return None
+
+		self.raptor.Debug("Writing Makefile '%s'" % (str(toplevel)))
+
+		self.toplevel = toplevel
+
+		# create the top-level makefiles
+		makefileset = None
+
+		try:
+			makefileset = MakefileSet(directory = str(toplevel.Dir()),
+										   selectors = self.selectors,
+										   filenamebase = str(toplevel.File()),
+										   prologue = self.makefile_prologue,
+										   epilogue = self.makefile_epilogue,
+										   defaulttargets = self.defaultTargets)
+
+			# are we pruning duplicates?
+			self.prune = self.raptor.pruneDuplicateMakefiles
+			self.hashes = set()
+
+			# are we writing one Makefile or lots?
+			self.many = not self.raptor.writeSingleMakefile
+
+			# add a makefile for each spec under each config
+			config_makefileset = makefileset
+			for c in configs:
+				if self.many:
+					config_makefileset = makefileset.createChild(c.name)
+
+				# make sure the config_wide spec item is put out first so that it
+				# can affect everything.
+				ordered_specs=[]
+				config_wide_spec = None
+				for s in specs:
+					if s.name == "config_wide":
+						config_wide_spec = s
+					else:
+						ordered_specs.append(s)
+
+				if config_wide_spec is not None:
+					config_wide_spec.Configure(c, cache = self.raptor.cache)
+					self.WriteConfiguredSpec(config_makefileset, config_wide_spec, c, True)
+
+				for s in ordered_specs:
+					s.Configure(c, cache = self.raptor.cache)
+					self.WriteConfiguredSpec(config_makefileset, s, c, False)
+
+			makefileset.close()
+		except Exception,e:
+			tb = traceback.format_exc()
+			if not self.raptor.debugOutput:
+				tb=""
+			self.raptor.Error("Failed to write makefile '%s': %s : %s" % (str(toplevel),str(e),tb))
+			makefileset = None
+
+		return makefileset
+
+
+	def WriteConfiguredSpec(self, parentMakefileSet, spec, config, useAllInterfaces):
+		# ignore this spec if it is empty
+		hasInterface = spec.HasInterface()
+		childSpecs = spec.GetChildSpecs()
+
+		if not hasInterface and not childSpecs:
+			return
+
+		parameters = []
+		dupe = True
+		iface = None
+		guard = None
+		if hasInterface:
+			# find the Interface (it may be a ref)
+			try:
+				iface = spec.GetInterface(self.raptor.cache)
+
+			except raptor_data.MissingInterfaceError, e:	
+				self.raptor.Error("No interface for '%s'", spec.name)
+				return
+
+			if iface.abstract:
+				self.raptor.Error("Abstract interface '%s' for '%s'",
+								  iface.name, spec.name)
+				return
+
+			# we need to guard the FLM call with a hash based on all the
+			# parameter values so that duplicate calls cannot be made.
+			# So we need to find all the values before we can write
+			# anything out.
+			md5hash = hashlib.md5()
+			md5hash.update(iface.name)
+
+			# we need an Evaluator to get parameter values for this
+			# Specification in the context of this Configuration
+			evaluator = self.raptor.GetEvaluator(spec, config)
+
+			def addparam(k, value, default):
+				if value == None:
+					if p.default != None:
+						value = p.default
+					else:
+						self.raptor.Error("%s undefined for '%s'",
+										  k, spec.name)
+						value = ""
+
+				parameters.append((k, value))
+				md5hash.update(value)
+
+			# parameters required by the interface
+			for p in iface.GetParams(self.raptor.cache):
+				val = evaluator.Resolve(p.name)
+				addparam(p.name,val,p.default)
+
+			# Use Patterns to fetch a group of parameters
+			for g in iface.GetParamGroups(self.raptor.cache):
+				for k,v in evaluator.ResolveMatching(g.patternre):
+					addparam(k,v,g.default)
+
+			hash = md5hash.hexdigest()
+			dupe = hash in self.hashes
+
+			self.hashes.add(hash)
+
+		# we only create a Makefile if we have a new FLM call to contribute,
+		# OR we are not pruning duplicates (guarding instead)
+		# OR we have some child specs that need something to include them.
+		if dupe and self.prune and not childSpecs:
+			return
+
+		makefileset = parentMakefileSet
+		# Create a new layer of makefiles?
+		if self.many:
+			makefileset = makefileset.createChild(spec.name)
+
+		if not (self.prune and dupe):
+			if self.prune:
+				guard = ""
+			else:
+				guard = "guard_" + hash
+
+		# generate the call to the FLM
+		if iface is not None:
+			makefileset.addCall(spec.name, config.name, iface.name, useAllInterfaces, iface.GetFLMIncludePath(self.raptor.cache), parameters, guard)
+
+		# recursive includes
+
+		for child in childSpecs:
+			self.WriteConfiguredSpec(makefileset, child, config, useAllInterfaces)
+
+		if self.many:
+			makefileset.close() # close child set of makefiles as we'll never see them again.
+
+	def Make(self, makefileset):
+		"run the make command"
+
+		if not self.valid:
+			return False
+	
+		if self.usetalon:
+			# Always use Talon since it does the XML not
+			# just descrambling
+			if not self.StartTalon() and not self.raptor.keepGoing:
+				self.Tidy()
+				return False
+		else:
+			# use the descrambler if we are doing a parallel build on
+			# a make engine which does not buffer each agent's output
+			if self.raptor.jobs > 1 and self.scrambled:
+				self.StartDescrambler()
+				if  not self.descrambler_started and not self.raptor.keepGoing:
+					self.Tidy()
+					return False
+			
+		# run any initialisation script
+		if self.initCommand:
+			self.raptor.Info("Running %s", self.initCommand)
+			if os.system(self.initCommand) != 0:
+				self.raptor.Error("Failed in %s", self.initCommand)
+				self.Tidy()
+				return False
+
+		# Save file names to a list, to allow the order to be reversed
+		fileName_list = list(makefileset.makefileNames())
+
+		# Iterate through args passed to raptor, searching for CLEAN or REALLYCLEAN
+		clean_flag = False
+		for arg in self.raptor.args:
+			clean_flag = ("CLEAN" in self.raptor.args) or \
+			            ("REALLYCLEAN" in self.raptor.args)
+
+		# Files should be deleted in the opposite order to the order
+		# they were built. So reverse file order if cleaning
+		if clean_flag:
+			fileName_list.reverse()
+
+		# Report number of makefiles to be built
+		self.raptor.InfoDiscovery(object_type = "makefile", count = len(fileName_list))
+
+		# Process each file in turn
+		for makefile in fileName_list:
+			if not os.path.exists(makefile):
+				self.raptor.Info("Skipping makefile %s", makefile)
+				continue
+			self.raptor.Info("Making %s", makefile)
+			# assemble the build command line
+			command = self.buildCommand
+
+			if self.makefileOption:
+				command += " " + self.makefileOption + " " + ' "' + str(makefile) + '" '
+
+			if self.raptor.keepGoing and self.keepGoingOption:
+				command += " " + self.keepGoingOption
+
+			if self.raptor.jobs > 1 and self.jobsOption:
+				command += " " + self.jobsOption +" "+ str(self.raptor.jobs)
+
+			# Set default options first so that they can be overridden by
+			# ones set by the --mo option on the raptor commandline:
+			command += " " + self.defaultMakeOptions
+			# Can supply options on the commandline to override default settings.
+			if len(self.raptor.makeOptions) > 0:
+				for o in self.raptor.makeOptions:
+					if o.find(";") != -1 or  o.find("\\") != -1:
+						command += "  " + "'" + o + "'"
+					else:
+						command += "  " + o
+
+			# Switch off dependency file including?
+			if self.raptor.noDependInclude or self.raptor.noDependGenerate:
+				command += " NO_DEPEND_INCLUDE=1"
+			
+			# Switch off dependency file generation (and, implicitly, inclusion)?
+			if self.raptor.noDependGenerate:
+				command += " NO_DEPEND_GENERATE=1"
+			
+			if self.usetalon:
+				# use the descrambler if we set it up
+				command += ' TALON_DESCRAMBLE=' 
+				if self.scrambled:
+					command += '1 '
+				else:
+					command += '0 '
+			else:
+				if self.descrambler_started:
+					command += ' DESCRAMBLE="' + self.descrambler + '"'
+			
+			# use the retry mechanism if requested
+			if self.raptor.tries > 1:
+				command += ' RECIPETRIES=' + str(self.raptor.tries)
+				command += ' TALON_RETRIES=' + str(self.raptor.tries - 1)
+
+			# targets go at the end, if the makefile supports them
+			addTargets = self.raptor.targets[:]
+			ignoreTargets = makefileset.ignoreTargets(makefile)
+			if addTargets and ignoreTargets:
+				for target in self.raptor.targets:
+					if re.match(ignoreTargets, target):
+						addTargets.remove(target)
+
+			if addTargets:
+				command += " " + " ".join(addTargets)
+
+			# Send stderr to a file so that it can't mess up the log (e.g.
+			# clock skew messages from some build engines scatter their
+			# output across our xml.
+			stderrfilename = makefile+'.stderr'
+			stdoutfilename = makefile+'.stdout'
+			command += " 2>'%s' " % stderrfilename
+
+			# Keep a copy of the stdout too in the case of using the 
+			# annofile - so that we can trap the problem that
+			# makes the copy-log-from-annofile workaround necessary
+			# and perhaps determine when we can remove it.
+			if self.copyLogFromAnnoFile:
+				command += " >'%s' " % stdoutfilename
+
+			# Substitute the makefile name for any occurrence of #MAKEFILE#
+			command = command.replace("#MAKEFILE#", str(makefile))
+
+			self.raptor.Info("Executing '%s'", command)
+
+			# execute the build.
+			# the actual call differs between Windows and Unix.
+			# bufsize=1 means "line buffered"
+			#
+			try:
+				# Time the build
+				self.raptor.InfoStartTime(object_type = "makefile",
+						task = "build", key = str(makefile))
+				
+				makeenv=os.environ.copy()
+				if self.usetalon:
+					makeenv['TALON_RECIPEATTRIBUTES']="none"
+					makeenv['TALON_SHELL']=self.talonshell
+					makeenv['TALON_BUILDID']=str(self.buildID)
+					makeenv['TALON_TIMEOUT']=str(self.talontimeout)
+
+				if self.raptor.filesystem == "unix":
+					p = subprocess.Popen([command], bufsize=65535,
+						stdout=subprocess.PIPE,
+						stderr=subprocess.STDOUT,
+						close_fds=True, env=makeenv, shell=True)
+				else:
+					p = subprocess.Popen(args = 
+						[raptor_data.ToolSet.shell, '-c', command],
+						bufsize=65535,
+						stdout=subprocess.PIPE,
+						stderr=subprocess.STDOUT,
+						shell = False,
+						universal_newlines=True, env=makeenv)
+				stream = p.stdout
+
+				inRecipe = False
+
+				if not self.copyLogFromAnnoFile:
+					for l in XMLEscapeLog(stream):
+						self.raptor.out.write(l)
+
+					returncode = p.wait()
+				else:
+					returncode = p.wait()
+
+					annofilename = self.annoFileName.replace("#MAKEFILE#", makefile)
+					self.raptor.Info("copylogfromannofile: Copying log from annotation file %s to work around a potential problem with the console output", annofilename)
+					try:
+						for l in XMLEscapeLog(AnnoFileParseOutput(annofilename)):
+							self.raptor.out.write(l)
+					except Exception,e:
+						self.raptor.Error("Couldn't complete stdout output from annofile %s for %s - '%s'", annofilename, command, str(e))
+
+
+				# Take all the stderr output that went into the .stderr file
+				# and put it back into the log, but safely so it can't mess up
+				# xml parsers.
+				try:
+					e = open(stderrfilename,"r")
+					for line in e:
+						self.raptor.out.write(escape(line))
+					e.close()
+				except Exception,e:
+					self.raptor.Error("Couldn't complete stderr output for %s - '%s'", command, str(e))
+				# Report end-time of the build
+				self.raptor.InfoEndTime(object_type = "makefile",
+						task = "build", key = str(makefile))
+
+				if returncode != 0  and not self.raptor.keepGoing:
+					self.Tidy()
+					return False
+
+			except Exception,e:
+				self.raptor.Error("Exception '%s' during '%s'", str(e), command)
+				self.Tidy()
+				# Still report end-time of the build
+				self.raptor.InfoEndTime(object_type = "Building", task = "Makefile",
+						key = str(makefile))
+				return False
+
+		# run any shutdown script
+		if self.shutdownCommand != None and self.shutdownCommand != "":
+			self.raptor.Info("Running %s", self.shutdownCommand)
+			if os.system(self.shutdownCommand) != 0:
+				self.raptor.Error("Failed in %s", self.shutdownCommand)
+				self.Tidy()
+				return False
+
+		self.Tidy()
+		return True
+
+	def Tidy(self):
+		if self.usetalon:
+			self.StopTalon() 
+		else:
+			"clean up after the make command"
+			self.StopDescrambler()
+
+	def StartTalon(self):
+		# the talon command
+		beginning = raptor.hostplatform_dir + "/bin"
+		if "win" in raptor.hostplatform:
+			end = ".exe"
+		else:
+			end = ""
+			
+		self.talonctl = str(self.raptor.home.Append(beginning, "talonctl"+end))
+			
+		# generate a unique build number
+		random.seed()
+		looking = True
+		tries = 0
+		while looking and tries < 100:
+			self.buildID = raptor.name + str(random.getrandbits(32))
+			
+			command = self.talonctl + " start"
+
+			os.environ["TALON_BUILDID"] = self.buildID
+			self.raptor.Info("Running %s", command)
+			looking = (os.system(command) != 0)
+			tries += 1
+		if looking:
+			self.raptor.Error("Failed to initialise the talon shell for this build")
+			self.talonctl = ""
+			return False
+		
+		return True
+	
+	def StopTalon(self):
+		if self.talonctl:
+			command = self.talonctl + " stop"
+			self.talonctl = ""
+			
+			self.raptor.Info("Running %s", command)
+			if os.system(command) != 0:
+				self.raptor.Error("Failed in %s", command)
+				return False
+			
+		return True
+	
+	def StartDescrambler(self):
+		# the descrambler command
+		beginning = raptor.hostplatform_dir + "/bin"
+		if "win" in raptor.hostplatform:
+			end = ".exe"
+		else:
+			end = ""
+
+		self.descrambler = str(self.raptor.home.Append(beginning, "sbs_descramble"+end))
+			
+		# generate a unique build number
+		random.seed()
+		looking = True
+		tries = 0
+		while looking and tries < 100:
+			buildID = raptor.name + str(random.getrandbits(32))
+
+			command = self.descrambler + " " + buildID + " start"
+			self.raptor.Info("Running %s", command)
+			looking = (os.system(command) != 0)
+			tries += 1
+
+		if looking:
+			self.raptor.Error("Failed to start the log descrambler")
+			self.descrambler_started = True
+			return False
+
+		self.descrambler_started = True
+		self.descrambler +=	" " + buildID
+
+		return  True
+
+	def StopDescrambler(self):
+		if self.descrambler_started:
+			command = self.descrambler + " stop"
+			self.descrambler = ""
+
+			self.raptor.Info("Running %s", command)
+			if os.system(command) != 0:
+				self.raptor.Error("Failed in %s", command)
+				return False
+		return True
+
+
+
+# raptor_make module functions
+
+
+# end of the raptor_make module
--- a/sbsv2/raptor/python/raptor_makefile.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/raptor_makefile.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,213 +1,227 @@
-#
-# 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: 
-# makefile module
-# This module is for writing calls to Function-Like Makefiles
-#
-
-import re
-import os
-import generic_path
-
-class MakefileSelector(object):
-	"""A "query" which is used to separate some flm interface calls
-	  into separate makefile trees."""
-	def __init__(self, name="default", interfacepattern=None, defaulttarget=None, ignoretargets=None):
-		self.name=name
-		if interfacepattern is not None:
-			self.interfacepattern=re.compile(interfacepattern, re.I)
-		else:
-			self.interfacepattern=None
-		self.defaulttarget=defaulttarget
-		self.ignoretargets=ignoretargets
-
-class Makefile(object):
-	"""Representation of the file that is created from the build specification 
-	   tree.
-	"""
-	def __init__(self, directory, selector, parent=None, filenamebase="Makefile", prologue=None, epilogue=None, defaulttargets=None):
-		self.filenamebase = filenamebase
-		self.directory = directory
-		if selector.name != "":
-			extension = "." + selector.name
-		else:
-			extension = ""
-		self.filename = generic_path.Join(directory,filenamebase + extension)
-		self.selector = selector
-		self.parent = parent
-		self.childlist = []
-		self.file = None
-		self.prologue = prologue
-		self.epilogue = epilogue
-		self.defaulttargets = defaulttargets
-		self.dead = False
-
-	def open(self):
-		if self.dead:
-			raise Exception, "Attempt to reopen completed makefile %s " % (self.filename)
-
-		if self.file is None:
-			directory = self.filename.Dir()
-			if not (str(directory) == "" or directory.Exists()):
-				try:
-					os.makedirs(directory.GetLocalString())
-				except Exception,e:
-					raise Exception, "Cannot make directory '%s' for file '%s' in '%s': %s " % (str(directory),str(self.filename),str(self.directory),str(e))
-
-			self.file = open(str(self.filename),"w+")
-			
-			self.file.write('# GENERATED MAKEFILE : DO NOT EDIT\n\n')
-			if self.selector.defaulttarget:
-				self.file.write('MAKEFILE_GROUP:=%s\n.PHONY:: %s\n%s:: # Default target\n' \
-							% (self.selector.defaulttarget, self.selector.defaulttarget, self.selector.defaulttarget))
-			else:
-				self.file.write('MAKEFILE_GROUP:=DEFAULT\n')
-			if self.prologue != None:
-				self.file.write(self.prologue)
-				
-			if self.defaulttargets != None:
-				self.file.write('# dynamic default targets\n')
-				for defaulttarget in self.defaulttargets:
-					self.file.write('.PHONY:: %s\n' % defaulttarget)
-					self.file.write('%s:\n' % defaulttarget)
-				self.file.write('\n')
-			
-	def addChild(self, child):
-		self.open()
-		self.file.write("include %s\n" % child.filename)
-		child.open()
-
-	def createChild(self, subdir):
-		child = Makefile(str(self.filename.Dir().Append(subdir)), self.selector, self, self.filenamebase, self.prologue, self.epilogue, self.defaulttargets)
-		self.addChild(child)
-		child.open()
-		return child
-
-	def addCall(self, specname, configname, ifname, useAllInterfaces, flmpath, parameters, guard = None):
-		"""Add an FLM call to the makefile.
-			specname is the name of the build specification (e.g. the mmp name)
-			configname is the name of the configuration which this call is made for
-			flmpath is the absolute path to the flm
-			parameters is an array of tuples, (paramname, paramvalue)	
-			guard is a hash value that should be unique to the FLM call
-
-		   This call will return False if the ifname does not match the selector for 
-		   the makefile. e.g. it prevents one from adding a resource FLM call to a
-		   makefile which is selecting export FLM calls. Selection is overridden if
-		   useAllInterfaces is True.
-		"""
-		# create the directory if it does not exist
-
-		if self.selector.interfacepattern is not None:
-			ifmatch = self.selector.interfacepattern.search(ifname)
-			if ifmatch == None and useAllInterfaces == False:
-				return False
-
-		self.open()
-		# now we can write the values into the makefile
-		self.file.write("# call %s\n" % flmpath)
-		self.file.write("SBS_SPECIFICATION:=%s\n" % specname)
-		self.file.write("SBS_CONFIGURATION:=%s\n\n" % configname)
-
-		if guard:
-			self.file.write("ifeq ($(%s),)\n%s:=1\n\n" % (guard, guard))
-		
-		for (p, value) in parameters:
-			self.file.write("%s:=%s\n" % (p, value))
-	
-		self.file.write("include %s\n" % flmpath)
-		self.file.write("MAKEFILE_LIST:= # work around potential gnu make stack overflow\n\n")
-		
-		if guard:
-			self.file.write("endif\n\n")
-
-		return True
-
-	def close(self):
-		if self.file is not None:
-			if self.epilogue != None:
-				self.file.write(self.epilogue)
-			self.file.write('# END OF GENERATED MAKEFILE : DO NOT EDIT\n')
-			self.file.close()
-			self.file = None
-			self.dead = True
-
-	def __del__(self):
-		self.close()
-			
-		
-
-class MakefileSet(object):
-	grouperselector = MakefileSelector(name="")
-	defaultselectors = [ 
-		MakefileSelector("export", '\.export$', "EXPORT"),
-		MakefileSelector("bitmap", '\.bitmap$', "BITMAP"),
-		MakefileSelector("resource", '\.resource$', "RESOURCE"),
-		MakefileSelector("default", '\.(?!export$|bitmap$|resource$).*$', "ALL")
-		]
-
-	def __init__(self, directory, selectors=defaultselectors, makefiles=None, parent=None, filenamebase="Makefile", prologue=None, epilogue=None, defaulttargets=None):
-		self.directory = generic_path.Path(directory)
-		self.filenamebase = filenamebase
-		self.parent = parent
-		if makefiles is not None:
-			self.makefiles = makefiles
-		else:
-			self.makefiles = []
-			for sel in selectors:
-				self.makefiles.append(Makefile(directory, sel, None, filenamebase, prologue, epilogue, defaulttargets))
-		self.groupermakefile = Makefile(directory, MakefileSet.grouperselector, None, filenamebase, "# GROUPER MAKEFILE\n\nALL::\n\n", "\n")
-		
-		for mf in self.makefiles:
-			self.groupermakefile.addChild(mf)
-
-
-	def createChild(self, subdir):
-		"""Create a set of "sub" makefiles that are included by this set."""
-		newmakefiles = []
-		for mf in self.makefiles:
-			newmf = mf.createChild(subdir)
-			newmakefiles.append(newmf)
-
-		newset = MakefileSet(str(self.directory.Append(subdir)), None, newmakefiles, self, self.filenamebase)
-		self.groupermakefile.addChild(newset.groupermakefile)
-
-		return newset
-
-	def addCall(self, specname, configname, ifname, useAllInterfaces, flmpath, parameters, guard = None):
-		"""Find out which makefiles to write this FLM call to 
-		   and write it to those (e.g. the exports makefile) """
-		for f in self.makefiles:
-			f.addCall(specname, configname, ifname, useAllInterfaces, flmpath, parameters, guard)
-
-	def makefileNames(self):
-		for mf in self.makefiles:
-			yield str(mf.filename)
-	
-	def ignoreTargets(self, makefile):
-		"""Get hold of a makefile's selector based on its name and
-		   determine whether it ignores targets based on a regexp."""
-		for mf in self.makefiles:
-			filename = str(mf.filename)			
-			if filename == makefile:
-				return mf.selector.ignoretargets 
-		return None
-
-	def close(self):
-		for mf in self.makefiles:
-			mf.close()
-		self.groupermakefile.close()
-
-	def __del__(self):
-		self.close()
+#
+# 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: 
+# makefile module
+# This module is for writing calls to Function-Like Makefiles
+#
+
+import re
+import os
+import generic_path
+
+class MakefileSelector(object):
+	"""A "query" which is used to separate some flm interface calls
+	  into separate makefile trees."""
+	def __init__(self, name="default", interfacepattern=None, defaulttarget=None, ignoretargets=None):
+		self.name=name
+		if interfacepattern is not None:
+			self.interfacepattern=re.compile(interfacepattern, re.I)
+		else:
+			self.interfacepattern=None
+		self.defaulttarget=defaulttarget
+		self.ignoretargets=ignoretargets
+
+class Makefile(object):
+	"""Representation of the file that is created from the build specification 
+	   tree.
+	"""
+	def __init__(self, directory, selector, parent=None, filenamebase="Makefile", prologue=None, epilogue=None, defaulttargets=None):
+		self.filenamebase = filenamebase
+		self.directory = directory
+		if selector.name != "":
+			extension = "." + selector.name
+		else:
+			extension = ""
+		self.filename = generic_path.Join(directory,filenamebase + extension)
+		self.selector = selector
+		self.parent = parent
+		self.childlist = []
+		self.file = None
+		self.prologue = prologue
+		self.epilogue = epilogue
+		self.defaulttargets = defaulttargets
+		self.dead = False
+
+	def open(self):
+		if self.dead:
+			raise Exception, "Attempt to reopen completed makefile %s " % (self.filename)
+
+		if self.file is None:
+			directory = self.filename.Dir()
+			if not (str(directory) == "" or directory.Exists()):
+				try:
+					os.makedirs(directory.GetLocalString())
+				except Exception,e:
+					raise Exception, "Cannot make directory '%s' for file '%s' in '%s': %s " % (str(directory),str(self.filename),str(self.directory),str(e))
+
+			self.file = open(str(self.filename),"w+")
+			
+			self.file.write('# GENERATED MAKEFILE : DO NOT EDIT\n\n')
+			if self.selector.defaulttarget:
+				self.file.write('MAKEFILE_GROUP:=%s\n.PHONY:: %s\n%s:: # Default target\n' \
+							% (self.selector.defaulttarget, self.selector.defaulttarget, self.selector.defaulttarget))
+			else:
+				self.file.write('MAKEFILE_GROUP:=DEFAULT\n')
+			if self.prologue != None:
+				self.file.write(self.prologue)
+				
+			if self.defaulttargets != None:
+				self.file.write('# dynamic default targets\n')
+				for defaulttarget in self.defaulttargets:
+					self.file.write('.PHONY:: %s\n' % defaulttarget)
+					self.file.write('%s:\n' % defaulttarget)
+				self.file.write('\n')
+			
+	def addChild(self, child):
+		self.open()
+		self.file.write("include %s\n" % child.filename)
+		child.open()
+
+	def createChild(self, subdir):
+		child = Makefile(str(self.filename.Dir().Append(subdir)), self.selector, self, self.filenamebase, self.prologue, self.epilogue, self.defaulttargets)
+		self.addChild(child)
+		child.open()
+		return child
+
+	def addCall(self, specname, configname, ifname, useAllInterfaces, flmpath, parameters, guard = None):
+		"""Add an FLM call to the makefile.
+			specname is the name of the build specification (e.g. the mmp name)
+			configname is the name of the configuration which this call is made for
+			flmpath is the absolute path to the flm
+			parameters is an array of tuples, (paramname, paramvalue)	
+			guard is a hash value that should be unique to the FLM call
+
+		   This call will return False if the ifname does not match the selector for 
+		   the makefile. e.g. it prevents one from adding a resource FLM call to a
+		   makefile which is selecting export FLM calls. Selection is overridden if
+		   useAllInterfaces is True.
+		"""
+		# create the directory if it does not exist
+
+		if self.selector.interfacepattern is not None:
+			ifmatch = self.selector.interfacepattern.search(ifname)
+			if ifmatch == None and useAllInterfaces == False:
+				return False
+
+		self.open()
+		# now we can write the values into the makefile
+		self.file.write("# call %s\n" % flmpath)
+		self.file.write("SBS_SPECIFICATION:=%s\n" % specname)
+		self.file.write("SBS_CONFIGURATION:=%s\n\n" % configname)
+
+		if guard:
+			self.file.write("ifeq ($(%s),)\n%s:=1\n\n" % (guard, guard))
+		
+		for (p, value) in parameters:
+			self.file.write("%s:=%s\n" % (p, value))
+	
+		self.file.write("include %s\n" % flmpath)
+		self.file.write("MAKEFILE_LIST:= # work around potential gnu make stack overflow\n\n")
+		
+		if guard:
+			self.file.write("endif\n\n")
+
+		return True
+
+	def addInclude(self, makefilename):
+		"""
+		"""
+		# create the directory if it does not exist
+
+		self.open()
+		# now we can write the values into the makefile
+		self.file.write("include %s\n" % (makefilename+"."+self.selector.name))
+
+	def close(self):
+		if self.file is not None:
+			if self.epilogue != None:
+				self.file.write(self.epilogue)
+			self.file.write('# END OF GENERATED MAKEFILE : DO NOT EDIT\n')
+			self.file.close()
+			self.file = None
+			self.dead = True
+
+	def __del__(self):
+		self.close()
+			
+		
+
+class MakefileSet(object):
+	grouperselector = MakefileSelector(name="")
+	defaultselectors = [ 
+		MakefileSelector("export", '\.export$', "EXPORT"),
+		MakefileSelector("bitmap", '\.bitmap$', "BITMAP"),
+		MakefileSelector("resource", '\.resource$', "RESOURCE"),
+		MakefileSelector("default", '\.(?!export$|bitmap$|resource$).*$', "ALL")
+		]
+
+	def __init__(self, directory, selectors=defaultselectors, makefiles=None, parent=None, filenamebase="Makefile", prologue=None, epilogue=None, defaulttargets=None):
+		self.directory = generic_path.Path(directory)
+		self.filenamebase = filenamebase
+		self.parent = parent
+		if makefiles is not None:
+			self.makefiles = makefiles
+		else:
+			self.makefiles = []
+			for sel in selectors:
+				self.makefiles.append(Makefile(directory, sel, None, filenamebase, prologue, epilogue, defaulttargets))
+		self.groupermakefile = Makefile(directory, MakefileSet.grouperselector, None, filenamebase, "# GROUPER MAKEFILE\n\nALL::\n\n", "\n")
+		
+		for mf in self.makefiles:
+			self.groupermakefile.addChild(mf)
+
+
+	def createChild(self, subdir):
+		"""Create a set of "sub" makefiles that are included by this set."""
+		newmakefiles = []
+		for mf in self.makefiles:
+			newmf = mf.createChild(subdir)
+			newmakefiles.append(newmf)
+
+		newset = MakefileSet(str(self.directory.Append(subdir)), None, newmakefiles, self, self.filenamebase)
+		self.groupermakefile.addChild(newset.groupermakefile)
+
+		return newset
+
+	def addCall(self, specname, configname, ifname, useAllInterfaces, flmpath, parameters, guard = None):
+		"""Find out which makefiles to write this FLM call to 
+		   and write it to those (e.g. the exports makefile) """
+		for f in self.makefiles:
+			f.addCall(specname, configname, ifname, useAllInterfaces, flmpath, parameters, guard)
+
+	def addInclude(self, makefilename):
+		"""include a makefile from each of the makefiles in the set - has the selector name appended to it."""
+		for f in self.makefiles:
+			f.addInclude(makefilename)
+
+	def makefileNames(self):
+		for mf in self.makefiles:
+			yield str(mf.filename)
+	
+	def ignoreTargets(self, makefile):
+		"""Get hold of a makefile's selector based on its name and
+		   determine whether it ignores targets based on a regexp."""
+		for mf in self.makefiles:
+			filename = str(mf.filename)			
+			if filename == makefile:
+				return mf.selector.ignoretargets 
+		return None
+
+	def close(self):
+		for mf in self.makefiles:
+			mf.close()
+		self.groupermakefile.close()
+
+	def __del__(self):
+		self.close()
--- a/sbsv2/raptor/python/raptor_meta.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/raptor_meta.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,3245 +1,3354 @@
-#
-# 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 module includes classes that process bld.inf and .mmp files to
-# generate Raptor build specifications
-#
-
-import copy
-import re
-import os.path
-import shutil
-import stat
-import hashlib
-import base64
-
-import raptor
-import raptor_data
-import raptor_utilities
-import raptor_xml
-import generic_path
-import subprocess
-import zipfile
-from mmpparser import *
-
-import time
-
-
-PiggyBackedBuildPlatforms = {'ARMV5':['GCCXML']}
-
-PlatformDefaultDefFileDir = {'WINSCW':'bwins',
-				  'ARMV5' :'eabi',
-				  'ARMV5SMP' :'eabi',
-				  'GCCXML':'eabi',
-				  'ARMV6':'eabi',
-				  'ARMV7' : 'eabi',
-				  'ARMV7SMP' : 'eabi'}
-
-def getVariantCfgDetail(aEPOCROOT, aVariantCfgFile):
-	"""Obtain pertinent build related detail from the Symbian variant.cfg file.
-
-	This variant.cfg file, usually located relative to $(EPOCROOT), contains:
-	(1) The $(EPOCROOT) relative location of the primary .hrh file used to configure the specific OS variant build
-	(2) A flag determining whether ARMV5 represents an ABIV1 or ABIV2 build (currently unused by Raptor)."""
-
-	variantCfgDetails = {}
-	variantCfgFile = None
-
-	try:
-		variantCfgFile = open(str(aVariantCfgFile))
-	except IOError, (number, message):
-		raise MetaDataError("Could not read variant configuration file "+str(aVariantCfgFile)+" ("+message+")")
-
-	for line in variantCfgFile.readlines():
-		if re.search('^(\s$|\s*#)', line):
-			continue
-		# Note that this detection of the .hrh file matches the command line build i.e. ".hrh" somewhere
-		# in the specified line
-		elif re.search('\.hrh', line, re.I):
-			variantHrh = line.strip()
-			if variantHrh.startswith('\\') or variantHrh.startswith('/'):
-				variantHrh = variantHrh[1:]
-			variantHrh = aEPOCROOT.Append(variantHrh)
-			variantCfgDetails['VARIANT_HRH'] = variantHrh
-		else:
-			lineContent = line.split()
-
-			if len(lineContent) == 1:
-				variantCfgDetails[lineContent.pop(0)] = 1
-			else:
-				variantCfgDetails[lineContent.pop(0)] = lineContent
-
-	variantCfgFile.close()
-
-	if not variantCfgDetails.has_key('VARIANT_HRH'):
-		raise MetaDataError("No variant file specified in "+str(aVariantCfgFile))
-	if not variantHrh.isFile():
-		raise MetaDataError("Variant file "+str(variantHrh)+" does not exist")
-
-	return variantCfgDetails
-
-def getOsVerFromKifXml(aPathToKifXml):
-	"""Obtain the OS version from the kif.xml file located at $EPOCROOT/epoc32/data/kif.xml.
-
-	If successful, the function returns a string such as "v95" to indicate 9.5; None is
-	returned if for any reason the function cannot determine the OS version."""
-
-	releaseTagName = "ki:release"
-	osVersion = None
-
-	import xml.dom.minidom
-
-	try:
-		# Parsed document object
-		kifDom = xml.dom.minidom.parse(str(aPathToKifXml))
-
-		# elements - the elements whose names are releaseTagName
-		elements = kifDom.getElementsByTagName(releaseTagName)
-
-		# There should be exactly one of the elements whose name is releaseTagName
-		# If more than one, osVersion is left as None, since the version should be
-		# unique to the kif.xml file
-		if len(elements) == 1:
-			osVersionTemp = elements[0].getAttribute("version")
-			osVersion = "v" + osVersionTemp.replace(".", "")
-
-		kifDom.unlink() # Clean up
-
-	except:
-		# There's no documentation on which exceptions are raised by these functions.
-		# We catch everything and assume any exception means there was a failure to
-		# determine OS version. None is returned, and the code will fall back
-		# to looking at the buildinfo.txt file.
-		pass
-
-	return osVersion
-
-def getOsVerFromBuildInfoTxt(aPathToBuildInfoTxt):
-	"""Obtain the OS version from the buildinfo.txt file located at $EPOCROOT/epoc32/data/buildinfo.txt.
-
-	If successful, the function returns a string such as "v95" to indicate 9.5; None is
-	returned if for any reason the function cannot determine the OS version.
-
-	The file $EPOCROOT/epoc32/data/buildinfo.txt is presumed to exist. The client code should
-	handle existance/non-existance."""
-
-	pathToBuildInfoTxt = str(aPathToBuildInfoTxt) # String form version of path to buildinfo.txt
-
-	# Open the file for reading; throw an exception if it could not be read - note that
-	# it should exist at this point.
-	try:
-		buildInfoTxt = open(pathToBuildInfoTxt)
-	except IOError, (number, message):
-		raise MetaDataError("Could not read buildinfo.txt file at" + pathToBuildInfoTxt + ": (" + message + ")")
-
-	# Example buildinfo.txt contents:
-	#
-	# DeviceFamily               100
-	# DeviceFamilyRev            0x900
-	# ManufacturerSoftwareBuild  M08765_Symbian_OS_v9.5
-	#
-	# Regexp to match the line containing the OS version
-	# Need to match things like M08765_Symbian_OS_v9.5 and M08765_Symbian_OS_vFuture
-	# So for the version, match everything except whitespace after v. Whitespace
-	# signifies the end of the regexp.
-	osVersionMatcher = re.compile('.*_Symbian_OS_v([^\s]*)', re.I)
-	osVersion = None
-
-	# Search for a regexp match over all the times in the file
-	# Note: if two or more lines match the search pattern then
-	# the latest match will overwrite the osVersion string.
-	for line in buildInfoTxt:
-		matchResult = osVersionMatcher.match(line)
-		if matchResult:
-			result = matchResult.groups()
-			osVersion = "v" +  str(reduce(lambda x, y: x + y, result))
-			osVersion = osVersion.replace(".", "")
-
-	buildInfoTxt.close() # Clean-up
-
-	return osVersion
-
-def getBuildableBldInfBuildPlatforms(aBldInfBuildPlatforms,
-									aDefaultOSBuildPlatforms,
-									aBaseDefaultOSBuildPlatforms,
-									aBaseUserDefaultOSBuildPlatforms):
-	"""Obtain a set of build platform names supported by a bld.inf file
-
-	Build platform deduction is based on both the contents of the PRJ_PLATFORMS section of
-	a bld.inf file together with a hard-coded set of default build platforms supported by
-	the build system itself."""
-
-	expandedBldInfBuildPlatforms = []
-	removePlatforms = set()
-
-	for bldInfBuildPlatform in aBldInfBuildPlatforms:
-		if bldInfBuildPlatform.upper() == "DEFAULT":
-			expandedBldInfBuildPlatforms.extend(aDefaultOSBuildPlatforms.split())
-		elif bldInfBuildPlatform.upper() == "BASEDEFAULT":
-			expandedBldInfBuildPlatforms.extend(aBaseDefaultOSBuildPlatforms.split())
-		elif bldInfBuildPlatform.upper() == "BASEUSERDEFAULT":
-			expandedBldInfBuildPlatforms.extend(aBaseUserDefaultOSBuildPlatforms.split())
-		elif bldInfBuildPlatform.startswith("-"):
-			removePlatforms.add(bldInfBuildPlatform.lstrip("-").upper())
-		else:
-			expandedBldInfBuildPlatforms.append(bldInfBuildPlatform.upper())
-
-	if len(expandedBldInfBuildPlatforms) == 0:
-		expandedBldInfBuildPlatforms.extend(aDefaultOSBuildPlatforms.split())
-
-	# make a set of platforms that can be built
-	buildableBldInfBuildPlatforms = set(expandedBldInfBuildPlatforms)
-
-	# Add platforms that are buildable by virtue of the presence of another
-	for piggyBackedPlatform in PiggyBackedBuildPlatforms:
-		if piggyBackedPlatform in buildableBldInfBuildPlatforms:
-			buildableBldInfBuildPlatforms.update(PiggyBackedBuildPlatforms.get(piggyBackedPlatform))
-
-	# Remove platforms that were negated
-	buildableBldInfBuildPlatforms -= removePlatforms
-
-	return buildableBldInfBuildPlatforms
-
-
-def getPreProcessorCommentDetail (aPreProcessorComment):
-	"""Takes a preprocessor comment and returns an array containing the filename and linenumber detail."""
-
-	commentDetail = []
-	commentMatch = re.search('# (?P<LINENUMBER>\d+) "(?P<FILENAME>.*)"', aPreProcessorComment)
-
-	if commentMatch:
-		filename = commentMatch.group('FILENAME')
-		filename = os.path.abspath(filename)
-		filename = re.sub(r'\\\\', r'\\', filename)
-		filename = re.sub(r'//', r'/', filename)
-		filename = generic_path.Path(filename)
-		linenumber = int (commentMatch.group('LINENUMBER'))
-
-		commentDetail.append(filename)
-		commentDetail.append(linenumber)
-
-	return commentDetail
-
-
-# Classes
-
-class MetaDataError(Exception):
-	"""Fatal error wrapper, to be thrown directly back to whatever is calling."""
-
-	def __init__(self, aText):
-		self.Text = aText
-	def __str__(self):
-		return repr(self.Text)
-
-
-class PreProcessedLine(str):
-	"""Custom string class that accepts filename and line number information from
-	a preprocessed context."""
-
-	def __new__(cls, value, *args, **keywargs):
-		return str.__new__(cls, value)
-
-	def __init__(self, value, aFilename, aLineNumber):
-		self.filename = aFilename
-		self.lineNumber = aLineNumber
-
-	def getFilename (self):
-		return self.filename
-
-	def getLineNumber (self):
-		return self.lineNumber
-
-class PreProcessor(raptor_utilities.ExternalTool):
-	"""Preprocessor wrapper suitable for Symbian metadata file processing."""
-
-	def __init__(self, aPreProcessor,
-				 aStaticOptions,
-				 aIncludeOption,
-				 aMacroOption,
-				 aPreIncludeOption,
-				 aRaptor):
-		raptor_utilities.ExternalTool.__init__(self, aPreProcessor)
-		self.__StaticOptions = aStaticOptions
-		self.__IncludeOption = aIncludeOption
-		self.__MacroOption = aMacroOption
-		self.__PreIncludeOption = aPreIncludeOption
-
-		self.filename = ""
-		self.__Macros = []
-		self.__IncludePaths = []
-		self.__PreIncludeFile = ""
-		self.raptor = aRaptor
-
-	def call(self, aArgs, sourcefilename):
-		""" Override call so that we can do our own error handling."""
-		tool = self._ExternalTool__Tool
-		try:
-			commandline = tool + " " + aArgs + " " + str(sourcefilename)
-
-			# the actual call differs between Windows and Unix
-			if raptor_utilities.getOSFileSystem() == "unix":
-				p = subprocess.Popen(commandline, \
-									 shell=True, bufsize=65535, \
-									 stdin=subprocess.PIPE, \
-									 stdout=subprocess.PIPE, \
-									 stderr=subprocess.PIPE, \
-									 close_fds=True)
-			else:
-				p = subprocess.Popen(commandline, \
-									 bufsize=65535, \
-									 stdin=subprocess.PIPE, \
-									 stdout=subprocess.PIPE, \
-									 stderr=subprocess.PIPE, \
-									 universal_newlines=True)
-
-			# run the command and wait for all the output
-			(self._ExternalTool__Output, errors) = p.communicate()
-
-			if self.raptor.debugOutput:
-				self.raptor.Debug("Preprocessing Start %s", str(sourcefilename))
-				self.raptor.Debug("Output:\n%s", self._ExternalTool__Output)
-				self.raptor.Debug("Errors:\n%s", errors)
-				self.raptor.Debug("Preprocessing End %s", str(sourcefilename))
-
-			incRE = re.compile("In file included from")
-			fromRE = re.compile(r"\s+from")
-			warningRE = re.compile("warning:|pasting.+token|from.+:")
-			remarkRE = re.compile("no newline at end of file|does not give a valid preprocessing token")
-
-			actualErr = False
-			if errors != "":
-				for error in errors.splitlines():
-					if incRE.search(error) or fromRE.search(error):
-						continue
-					if not remarkRE.search(error):
-						if warningRE.search(error):
-							self.raptor.Warn("%s: %s", tool, error)
-						else:
-							self.raptor.Error("%s: %s", tool, error)
-							actualErr = True
-			if actualErr:
-				raise MetaDataError("Errors in %s" % str(sourcefilename))
-
-		except Exception,e:
-			raise MetaDataError("Preprocessor exception: %s" % str(e))
-
-		return 0	# all OK
-
-	def setMacros(self, aMacros):
-		self.__Macros = aMacros
-
-	def addMacro(self, aMacro):
-		self.__Macros.append(aMacro)
-
-	def addMacros(self, aMacros):
-		self.__Macros.extend(aMacros)
-
-	def getMacros(self):
-		return self.__Macros
-
-
-	def addIncludePath(self, aIncludePath):
-		p = str(aIncludePath)
-		if p == "":
-			self.raptor.Warn("attempt to set an empty preprocessor include path for %s" % str(self.filename))
-		else:
-			self.__IncludePaths.append(p)
-
-	def addIncludePaths(self, aIncludePaths):
-		for path in aIncludePaths:
-			self.addIncludePath(path)
-
-	def setIncludePaths(self, aIncludePaths):
-		self.__IncludePaths = []
-		self.addIncludePaths(aIncludePaths)
-
-	def setPreIncludeFile(self, aPreIncludeFile):
-		self.__PreIncludeFile = aPreIncludeFile
-
-	def preprocess(self):
-		preProcessorCall = self.__constructPreProcessorCall()
-		returnValue = self.call(preProcessorCall, self.filename)
-
-		return self.getOutput()
-
-	def __constructPreProcessorCall(self):
-
-		call = self.__StaticOptions
-
-		if self.__PreIncludeFile:
-			call += " " + self.__PreIncludeOption
-			call += " " + str(self.__PreIncludeFile)
-
-		for macro in self.__Macros:
-			call += " " + self.__MacroOption + macro
-
-		for includePath in self.__IncludePaths:
-			call += " " + self.__IncludeOption
-			call += " " + str(includePath)
-
-		return call
-
-
-class MetaDataFile(object):
-	"""A generic representation of a Symbian metadata file
-
-	Symbian metadata files are subject to preprocessing, primarily with macros based
-	on the selected build platform.  This class provides a generic means of wrapping
-	up the preprocessing of such files."""
-
-	def __init__(self, aFilename, gnucpp, aRootLocation=None, log=None):
-		"""
-		@param aFilename	An MMP, bld.inf or other preprocessable build spec file
-		@param aDefaultPlatform  Default preprocessed version of this file
-		@param aCPP 		location of GNU CPP
-		@param log 		A class with Debug(<string>), Info(<string>) and Error(<string>) methods
-		"""
-		self.filename = aFilename
-		self.__RootLocation = aRootLocation
-		# Dictionary with key of build platform and a text string of processed output as values
-		self.__PreProcessedContent = {}
-		self.log = log
-
-		self.__gnucpp = gnucpp
-		if gnucpp is None:
-			raise ValueError('gnucpp must be set')
-
-	def depspath(self, platform):
-	   """ Where does dependency information go relative to platform's SBS_BUILD_DIR?
-	       Subclasses should redefine this
-	   """
-	   return str(platform['SBS_BUILD_DIR']) + "/" + str(self.__RootLocation) + "." + platform['key_md5'] + ".d"
-
-	def getContent(self, aBuildPlatform):
-
-		key = aBuildPlatform['key']
-
-		config_macros = []
-
-		adepfilename = self.depspath(aBuildPlatform)
-		generateDepsOptions = ""
-		if adepfilename:
-
-			if raptor_utilities.getOSPlatform().startswith("win"):
-				metatarget = "$(PARSETARGET)"
-			else:
-				metatarget = "'$(PARSETARGET)'"
-			generateDepsOptions = "-MD -MF%s -MT%s" % (adepfilename, metatarget)
-			aBuildPlatform['METADEPS'].append((adepfilename, metatarget))
-			try:
-				os.makedirs(os.path.dirname(adepfilename))
-			except Exception, e:
-				self.log.Debug("Couldn't make bldinf outputpath for dependency generation")
-
-		config_macros = (aBuildPlatform['PLATMACROS']).split()
-
-		if not key in self.__PreProcessedContent:
-
-			preProcessor = PreProcessor(self.__gnucpp, '-undef -nostdinc ' + generateDepsOptions + ' ',
-										'-I', '-D', '-include', self.log)
-			preProcessor.filename = self.filename
-
-			# always have the current directory on the include path
-			preProcessor.addIncludePath('.')
-
-			# the SYSTEMINCLUDE directories defined in the build config
-			# should be on the include path. This is added mainly to support
-			# Feature Variation as SYSTEMINCLUDE is usually empty at this point.
-			systemIncludes = aBuildPlatform['SYSTEMINCLUDE']
-			if systemIncludes:
-				preProcessor.addIncludePaths(systemIncludes.split())
-
-			preInclude = aBuildPlatform['VARIANT_HRH']
-
-			# for non-Feature Variant builds, the directory containing the HRH should
-			# be on the include path
-			if not aBuildPlatform['ISFEATUREVARIANT']:
-				preProcessor.addIncludePath(preInclude.Dir())
-
-			# and EPOCROOT/epoc32/include
-			preProcessor.addIncludePath(aBuildPlatform['EPOCROOT'].Append('epoc32/include'))
-
-			# and the directory containing the bld.inf file
-			if self.__RootLocation is not None and str(self.__RootLocation) != "":
-				preProcessor.addIncludePath(self.__RootLocation)
-
-			# and the directory containing the file we are processing
-			preProcessor.addIncludePath(self.filename.Dir())
-
-			# there is always a pre-include file
-			preProcessor.setPreIncludeFile(preInclude)
-
-			macros = ["SBSV2"]
-
-			if config_macros:
-				macros.extend(config_macros)
-
-			if macros:
-				for macro in macros:
-					preProcessor.addMacro(macro + "=_____" +macro)
-
-			# extra "raw" macros that do not need protecting
-			preProcessor.addMacro("__GNUC__=3")
-
-			preProcessorOutput = preProcessor.preprocess()
-
-			# Resurrect preprocessing replacements
-			pattern = r'([\\|/]| |) ?_____(('+macros[0]+')'
-			for macro in macros[1:]:
-				pattern += r'|('+macro+r')'
-
-			pattern += r'\s*)'
-			# Work on all Macros in one substitution.
-			text = re.sub(pattern, r"\1\2", preProcessorOutput)
-			text = re.sub(r"\n[\t ]*", r"\n", text)
-
-			self.__PreProcessedContent[key] = text
-
-		return self.__PreProcessedContent[key]
-
-class MMPFile(MetaDataFile):
-	"""A generic representation of a Symbian metadata file
-
-	Symbian metadata files are subject to preprocessing, primarily with macros based
-	on the selected build platform.  This class provides a generic means of wrapping
-	up the preprocessing of such files."""
-
-	def __init__(self, aFilename, gnucpp, bldinf, log=None):
-		"""
-		@param aFilename	An MMP, bld.inf or other preprocessable build spec file
-		@param gnucpp 		location of GNU CPP
-		@param bldinf   	the bldinf file that this mmp comes from
-		@param log 			A class with Debug(<string>), Info(<string>) and Error(<string>) methods
-		"""
-		super(MMPFile, self).__init__(aFilename, gnucpp, str(bldinf.filename.Dir()), log)
-		self.__bldinf = bldinf
-
-		self.__gnucpp = gnucpp
-		if gnucpp is None:
-			raise ValueError('gnucpp must be set')
-
-	def depspath(self, platform):
-	   """ Where does dependency information go relative to platform's SBS_BUILD_DIR?
-	       Subclasses should redefine this
-	   """
-	   return self.__bldinf.outputpath(platform) + "/" + self.filename.File() + '.' + platform['key_md5'] + ".d"
-
-class Export(object):
-	"""Single processed PRJ_EXPORTS or PRJ_TESTEXPORTS entry from a bld.inf file"""
-
-	def getPossiblyQuotedStrings(cls,spec):
-		""" 	Split a string based on whitespace
-			but keep double quoted substrings together.
-		"""
-		inquotes=False
-		intokengap=False
-		sourcedest=[]
-		word = 0
-		for c in spec:
-			if c == '"':
-				if inquotes:
-					inquotes = False
-					word += 1
-					intokengap = True
-				else:
-					inquotes = True
-					intokengap = False
-				pass
-			elif c == ' ' or c == '\t':
-				if inquotes:
-					if len(sourcedest) == word:
-						sourcedest.append(c)
-					else:
-						sourcedest[word] += c
-				else:
-					if intokengap:
-						# gobble unquoted spaces
-						pass
-					else:
-						word += 1
-						intokengap=True
-				pass
-			else:
-				intokengap = False
-				if len(sourcedest) == word:
-					sourcedest.append(c)
-				else:
-					sourcedest[word] += c
-
-		return sourcedest
-
-	getPossiblyQuotedStrings = classmethod(getPossiblyQuotedStrings)
-
-
-	def __init__(self, aBldInfFile, aExportsLine, aType):
-		"""
-		Rules from the OS library for convenience:
-
-		For PRJ_TESTEXPORTS
-		source_file_1 [destination_file]
-		source_file_n [destination_file]
-		If the source file is listed with a relative path, the path will
-	 	  be considered relative to the directory containing the bld.inf file.
-		If a destination file is not specified, the source file will be copied
-		  to the directory containing the bld.inf file.
-		If a relative path is specified with the destination file, the path
-		  will be considered relative to directory containing the bld.inf file.
-
-		For PRJ_EXPORTS
-		source_file_1 [destination_file]
-		source_file_n [destination_file]
-		:zip zip_file [destination_path]
-
-		Note that:
-		If a source file is listed with a relative path, the path will be
-		considered relative to the directory containing the bld.inf file.
-
-		If a destination file is not specified, the source file will be copied
-		to epoc32\include\.
-
-		If a destination file is specified with the relative path, the path will
-		be considered relative to directory epoc32\include\.
-
-		If a destination begins with a drive letter, then the file is copied to
-		epoc32\data\<drive_letter>\<path>. For example,
-
-			mydata.dat e:\appdata\mydata.dat
-			copies mydata.dat to epoc32\data\e\appdata\mydata.dat.
-			You can use any driveletter between A and Z.
-
-		A line can start with the preface :zip. This instructs the build tools
-		to unzip the specified zip file to the specified destination path. If a
-		destination path is not specified, the source file will be unzipped in
-		the root directory.
-
-
-		"""
-
-		# Work out what action is required - unzip or copy?
-		action = "copy"
-		typematch = re.match(r'^\s*(?P<type>:zip\s+)?(?P<spec>[^\s].*[^\s])\s*$',aExportsLine, re.I)
-
-		spec = typematch.group('spec')
-		if spec == None:
-			raise ValueError('must specify at least a source file for an export')
-
-		if typematch.group('type') is not None:
-			action = "unzip"
-
-		# Split the spec into source and destination but take care
-		# to allow filenames with quoted strings.
-		exportEntries = Export.getPossiblyQuotedStrings(spec)
-
-		# Get the source path as specified by the bld.inf
-		source_spec = exportEntries.pop(0).replace(' ','%20')
-
-		# Resolve the source file
-		sourcepath = generic_path.Path(raptor_utilities.resolveSymbianPath(str(aBldInfFile), source_spec))
-
-		# Find it if the case of the filename is wrong:
-		# Carry on even if we don't find it
-		foundfile = sourcepath.FindCaseless()
-		if foundfile != None:
-			source = str(foundfile).replace(' ','%20')
-		else:
-			source = str(sourcepath).replace(' ','%20')
-
-
-		# Get the destination path as specified by the bld.inf
-		if len(exportEntries) > 0:
-			dest_spec = exportEntries.pop(0).replace(' ','%20')
-		else:
-			dest_spec = None
-		# Destination list - list of destinations. For the WINSCW resource building stage,
-		# files exported to the emulated drives and there are several locations, for example,
-		# PRJ_[TEST]EXPORTS
-		# 1234ABCD.SPD		z:/private/10009876/policy/1234ABCD.spd
-		# needs to end up copied in
-		# epoc32/data/z/private/10009876/policy/1234ABCD.spd *and* in
-		# epoc32/release/winscw/udeb/z/private/10009876/policy/1234ABCD.spd *and* in
-		# epoc32/release/winscw/urel/z/private/10009876/policy/1234ABCD.spd
-		dest_list = []
-
-		# Resolve the destination if one is specified
-		if dest_spec:
-			# check for troublesome characters
-			if ':' in dest_spec and not re.search('^[a-z]:', dest_spec, re.I):
-				raise ValueError("invalid filename " + dest_spec)
-
-			dest_spec = dest_spec.replace(' ','%20')
-			aSubType=""
-			if action == "unzip":
-				aSubType=":zip"
-				dest_spec = dest_spec.rstrip("\\/")
-
-			# Get the export destination(s) - note this can be a list of strings or just a string.
-			dest_list = raptor_utilities.resolveSymbianPath(str(aBldInfFile), dest_spec, aType, aSubType)
-
-			def process_dest(aDest):
-				if dest_spec.endswith('/') or  dest_spec.endswith('\\'):
-					m = generic_path.Path(source)
-					aDest += '/'+m.File()
-				return aDest
-
-			if isinstance(dest_list, list):
-				# Process each file in the list
-				dest_list = map(process_dest, dest_list)
-			else:
-				# Process the single destination
-				dest_list = process_dest(dest_list)
-
-		else:
-			# No destination was specified so we assume an appropriate one
-
-			dest_filename=generic_path.Path(source).File()
-
-			if aType == "PRJ_EXPORTS":
-				if action == "copy":
-					destination = '$(EPOCROOT)/epoc32/include/'+dest_filename
-				elif action == "unzip":
-					destination = '$(EPOCROOT)'
-			elif aType == "PRJ_TESTEXPORTS":
-				d = aBldInfFile.Dir()
-				if action == "copy":
-					destination = str(d.Append(dest_filename))
-				elif action == "unzip":
-					destination = "$(EPOCROOT)"
-			else:
-				raise ValueError("Export type should be 'PRJ_EXPORTS' or 'PRJ_TESTEXPORTS'. It was: "+str(aType))
-
-
-		self.__Source = source
-		if len(dest_list) > 0: # If the list has length > 0, this means there are several export destinations.
-			self.__Destination = dest_list
-		else: # Otherwise the list has length zero, so there is only a single export destination.
-			self.__Destination = destination
-		self.__Action = action
-
-	def getSource(self):
-		return self.__Source
-
-	def getDestination(self):
-		return self.__Destination # Note that this could be either a list, or a string, depending on the export destination
-
-	def getAction(self):
-		return self.__Action
-
-class ExtensionmakefileEntry(object):
-	def __init__(self, aGnuLine, aBldInfFile, tmp):
-
-		self.__BldInfFile = aBldInfFile
-		bldInfLocation = self.__BldInfFile.Dir()
-		biloc = str(bldInfLocation)
-		extInfLocation = tmp.filename.Dir()
-		eiloc = str(extInfLocation)
-
-		if eiloc is None or eiloc == "":
-			eiloc="." # Someone building with a relative raptor path
-		if biloc is None or biloc == "":
-			biloc="." # Someone building with a relative raptor path
-
-		self.__StandardVariables = {}
-		# Relative step-down to the root - let's try ignoring this for now, as it
-		# should amount to the same thing in a world where absolute paths are king
-		self.__StandardVariables['TO_ROOT'] = ""
-		# Top-level bld.inf location
-		self.__StandardVariables['TO_BLDINF'] = biloc
-		self.__StandardVariables['EXTENSION_ROOT'] = eiloc
-
-		# Get the directory and filename from the full path containing the extension makefile
-		self.__FullPath = generic_path.Join(eiloc,aGnuLine)
-		self.__FullPath = self.__FullPath.GetLocalString()
-		self.__Filename = os.path.split(self.__FullPath)[1]
-		self.__Directory = os.path.split(self.__FullPath)[0]
-
-	def getMakefileName(self):
-		return self.__Filename
-
-	def getMakeDirectory(self):
-		return self.__Directory
-
-	def getStandardVariables(self):
-		return self.__StandardVariables
-
-class Extension(object):
-	"""Single processed PRJ_EXTENSIONS or PRJ_TESTEXTENSIONS START EXTENSIONS...END block
-	from a bld.inf file"""
-
-	def __init__(self, aBldInfFile, aStartLine, aOptionLines, aBuildPlatform, aRaptor):
-		self.__BldInfFile = aBldInfFile
-		self.__Options = {}
-		self.interface = ""
-		self.__Raptor = aRaptor
-
-		makefile = ""
-		makefileMatch = re.search(r'^\s*START EXTENSION\s+(?P<MAKEFILE>\S+)\s*(?P<NAMETAG>\S*)$', aStartLine, re.I)
-
-		self.__RawMakefile = ""
-
-		if (makefileMatch):
-			self.__RawMakefile = makefileMatch.group('MAKEFILE')
-			self.nametag = makefileMatch.group('NAMETAG').lower()
-
-			# Ensure all \'s are translated into /'s if required
-			self.interface = self.__RawMakefile
-			self.interface = self.interface.replace("\\", "/").replace("/", ".")
-
-		# To support standalone testing, '$(' prefixed TEMs  are assumed to  start with
-		# a makefile variable and hence be fully located in FLM operation
-		if self.__RawMakefile.startswith("$("):
-			self.__Makefile = self.__RawMakefile + ".mk"
-		else:
-			self.__Makefile = '$(MAKEFILE_TEMPLATES)/' + self.__RawMakefile + ".mk"
-
-		for optionLine in aOptionLines:
-			optionMatch = re.search(r'^\s*(OPTION\s+)?(?P<VARIABLE>\S+)\s+(?P<VALUE>\S+.*)$',optionLine, re.I)
-			if optionMatch:
-				self.__Options[optionMatch.group('VARIABLE').upper()] = optionMatch.group('VALUE')
-
-		bldInfLocation = self.__BldInfFile.Dir()
-
-		biloc = str(bldInfLocation)
-		if biloc is None or biloc == "":
-			biloc="." # Someone building with a relative raptor path
-
-		extInfLocation = aStartLine.filename.Dir()
-
-		eiloc = str(extInfLocation)
-		if eiloc is None or eiloc == "":
-			eiloc="." # Someone building with a relative raptor path
-
-		self.__StandardVariables = {}
-		# Relative step-down to the root - let's try ignoring this for now, as it
-		# should amount to the same thing in a world where absolute paths are king
-		self.__StandardVariables['TO_ROOT'] = ""
-		# Top-level bld.inf location
-		self.__StandardVariables['TO_BLDINF'] = biloc
-		# Location of bld.inf file containing the current EXTENSION block
-		self.__StandardVariables['EXTENSION_ROOT'] = eiloc
-
-		# If the interface exists, this means it's not a Template Extension Makefile so don't look for a .meta file for it;
-		# so do nothing if it's not a template extension makefile
-		try:
-			self.__Raptor.cache.FindNamedInterface(str(self.interface), aBuildPlatform['CACHEID'])
-		except KeyError: # This means that this Raptor doesn't have the interface self.interface, so we are in a TEM
-			# Read extension meta file and get default options from it.  The use of TEM meta file is compulsory if TEM is used
-			metaFilename = "%s/epoc32/tools/makefile_templates/%s.meta" % (aBuildPlatform['EPOCROOT'], self.__RawMakefile)
-			metaFile = None
-			try:
-				metaFile = open(metaFilename, "r")
-			except IOError, e:
-				self.__warn("Extension: %s - cannot open Meta file: %s" % (self.__RawMakefile, metaFilename))
-
-			if metaFile:
-				for line in metaFile.readlines():
-					defaultOptionMatch = re.search(r'^OPTION\s+(?P<VARIABLE>\S+)\s+(?P<VALUE>\S+.*)$',line, re.I)
-					if defaultOptionMatch and defaultOptionMatch.group('VARIABLE').upper() not in self.__Options.keys():
-						self.__Options[defaultOptionMatch.group('VARIABLE').upper()] = defaultOptionMatch.group('VALUE')
-
-				metaFile.close()
-
-	def __warn(self, format, *extras):
-		if (self.__Raptor):
-			self.__Raptor.Warn(format, *extras)
-
-	def getIdentifier(self):
-		return re.sub (r'\\|\/|\$|\(|\)', '_', self.__RawMakefile)
-
-	def getMakefile(self):
-		return self.__Makefile
-
-	def getOptions(self):
-		return self.__Options
-
-	def getStandardVariables(self):
-		return self.__StandardVariables
-
-class MMPFileEntry(object):
-	def __init__(self, aFilename, aTestOption, aARMOption):
-		self.filename = aFilename
-		self.testoption = aTestOption
-		if aARMOption:
-			self.armoption = True
-		else:
-			self.armoption = False
-
-
-class BldInfFile(MetaDataFile):
-	"""Representation of a Symbian bld.inf file"""
-
-	def __init__(self, aFilename, gnucpp, log=None):
-		MetaDataFile.__init__(self, aFilename, gnucpp, None, log)
-		self.__Raptor = log
-		self.testManual = 0
-		self.testAuto = 0
-	# Generic
-
-	def getBuildPlatforms(self, aBuildPlatform):
-		platformList = []
-
-		for platformLine in self.__getSection(aBuildPlatform, 'PRJ_PLATFORMS'):
-			for platformEntry in platformLine.split():
-				platformList.append(platformEntry)
-
-		return platformList
-
-	# Build Platform Specific
-	def getMMPList(self, aBuildPlatform, aType="PRJ_MMPFILES"):
-		mmpFileList=[]
-		gnuList = []
-		makefileList = []
-		extFound = False
-		m = None
-
-		hashValue = {'mmpFileList': [] , 'gnuList': [], 'makefileList' : []}
-
-		for mmpFileEntry in self.__getSection(aBuildPlatform, aType):
-
-			actualBldInfRoot = mmpFileEntry.getFilename()
-			n = re.match('\s*(?P<makefiletype>(GNUMAKEFILE|N?MAKEFILE))\s+(?P<extmakefile>[^ ]+)\s*(support|manual)?\s*(?P<invalid>\S+.*)?\s*$',mmpFileEntry,re.I)
-			if n:
-
-				if (n.groupdict()['invalid']):
-					self.log.Error("%s (%d) : invalid .mmp file qualifier \"%s\"", mmpFileEntry.filename, mmpFileEntry.getLineNumber(), n.groupdict()['invalid'])
-				if raptor_utilities.getOSFileSystem() == "unix":
-					self.log.Warn("NMAKEFILE/GNUMAKEFILE/MAKEFILE keywords not supported on Linux")
-				else:
-					extmakefilearg = n.groupdict()['extmakefile']
-					bldInfDir = actualBldInfRoot.Dir()
-					extmakefilename = bldInfDir.Append(extmakefilearg)
-					extmakefile = ExtensionmakefileEntry(extmakefilearg, self.filename, mmpFileEntry)
-
-					if (n.groupdict()['makefiletype']).upper() == "GNUMAKEFILE":
-						gnuList.append(extmakefile)
-					else:
-						makefileList.append(extmakefile)
-			else:
-				# Currently there is only one possible option - build as arm.
-				# For TESTMMPFILES, the supported options are support, tidy, ignore, manual and build as arm
-				if aType.upper()=="PRJ_TESTMMPFILES":
-					if re.match('\s*(?P<name>[^ ]+)\s*(?P<baa>build_as_arm)?\s*(?P<support>support)?\s*(?P<ignore>ignore)?\s*(?P<tidy>tidy)?\s*(?P<manual>manual)?\s*(?P<invalid>\S+.*)?\s*$', mmpFileEntry, re.I):
-						m = re.match('\s*(?P<name>[^ ]+)\s*(?P<baa>build_as_arm)?\s*(?P<support>support)?\s*(?P<ignore>ignore)?\s*(?P<tidy>tidy)?\s*(?P<manual>manual)?\s*(?P<invalid>\S+.*)?\s*$', mmpFileEntry, re.I)
-				else:
-					if re.match('\s*(?P<name>[^ ]+)\s*(?P<baa>build_as_arm)?\s*(?P<invalid>\S+.*)?\s*$', mmpFileEntry, re.I):
-						m = re.match('\s*(?P<name>[^ ]+)\s*(?P<baa>build_as_arm)?\s*(?P<invalid>\S+.*)?\s*$', mmpFileEntry, re.I)
-
-			if m:
-				if (m.groupdict()['invalid']):
-					self.log.Error("%s (%d) : invalid .mmp file qualifier \"%s\"", mmpFileEntry.filename, mmpFileEntry.getLineNumber(), m.groupdict()['invalid'])
-
-				mmpFileName = m.groupdict()['name']
-				testmmpoption = "auto" # Setup tests to be automatic by default
-				tokens = m.groupdict()
-				for key,item in tokens.iteritems():
-					if key=="manual" and item=="manual":
-						testmmpoption = "manual"
-					elif key=="support" and item=="support":
-						testmmpoption = "support"
-					elif key=="ignore" and item=="ignore":
-						testmmpoption = "ignore"
-
-				buildasarm = False
-				if  m.groupdict()['baa']:
-					if m.groupdict()['baa'].lower() == 'build_as_arm':
-						buildasarm = True
-
-				if not mmpFileName.lower().endswith('.mmp'):
-					mmpFileName += '.mmp'
-				bldInfDir = actualBldInfRoot.Dir()
-				try:
-					mmpFileName = bldInfDir.Append(mmpFileName)
-					mmpfe = MMPFileEntry(mmpFileName, testmmpoption, buildasarm)
-					mmpFileList.append(mmpfe)
-				except ValueError, e:
-					self.log.Error("invalid .mmp file name: %s" % str(e))
-
-				m = None
-
-
-		hashValue['mmpFileList'] = mmpFileList
-		hashValue['gnuList'] = gnuList
-		hashValue['makefileList'] = makefileList
-
-		return hashValue
-
-	# Return a list of gnumakefiles used in the bld.inf
-	def getExtensionmakefileList(self, aBuildPlatform, aType="PRJ_MMPFILES",aString = ""):
-		extMakefileList=[]
-		m = None
-		for extmakeFileEntry in self.__getSection(aBuildPlatform, aType):
-
-			actualBldInfRoot = extmakeFileEntry.filename
-			if aType.upper()=="PRJ_TESTMMPFILES":
-				m = re.match('\s*GNUMAKEFILE\s+(?P<extmakefile>[^ ]+)\s*(?P<support>support)?\s*(?P<ignore>ignore)?\s*(?P<tidy>tidy)?\s*(?P<manual>manual)?\s*(?P<invalid>\S+.*)?\s*$',extmakeFileEntry,re.I)
-			else:
-				if aString == "gnumakefile":
-					m = re.match('\s*GNUMAKEFILE\s+(?P<extmakefile>[^ ]+)\s*(?P<invalid>\S+.*)?\s*$',extmakeFileEntry,re.I)
-				elif aString == "nmakefile":
-					m = re.match('\s*NMAKEFILE\s+(?P<extmakefile>[^ ]+)\s*(?P<invalid>\S+.*)?\s*$',extmakeFileEntry,re.I)
-				elif aString == "makefile":
-					m = re.match('\s*MAKEFILE\s+(?P<extmakefile>[^ ]+)\s*(?P<invalid>\S+.*)?\s*$',extmakeFileEntry,re.I)
-			if m:
-				if (m.groupdict()['invalid']):
-					self.log.Error("%s (%d) : invalid extension makefile qualifier \"%s\"", extmakeFileEntry.filename, extmakeFileEntry.getLineNumber(), m.groupdict()['invalid'])
-
-				extmakefilearg = m.groupdict()['extmakefile']
-				bldInfDir = actualBldInfRoot.Dir()
-				extmakefilename = bldInfDir.Append(extmakefilearg)
-				extmakefile = ExtensionmakefileEntry(extmakefilearg, self.filename, extmakeFileEntry)
-				extMakefileList.append(extmakefile)
-				m = None
-
-		return extMakefileList
-
-	def getTestExtensionmakefileList(self,aBuildPlatform,aString=""):
-		return self.getExtensionmakefileList(aBuildPlatform,"PRJ_TESTMMPFILES",aString)
-
-	def getTestMMPList(self, aBuildPlatform):
-		return self.getMMPList(aBuildPlatform, "PRJ_TESTMMPFILES")
-
-	def getRomTestType(self, aBuildPlatform):
-		testMMPList = self.getTestMMPList(aBuildPlatform)
-		for testMMPFileEntry in testMMPList['mmpFileList']:
-			if aBuildPlatform["TESTCODE"]:
-				# Calculate test type (manual or auto)
-				if testMMPFileEntry.testoption == "manual":
-					self.testManual += 1
-				if not (testMMPFileEntry.testoption == "support" or testMMPFileEntry.testoption == "manual" or testMMPFileEntry.testoption == "ignore"):
-					self.testAuto += 1
-		if self.testManual and self.testAuto:
-			return 'BOTH'
-		elif self.testAuto:
-			return 'AUTO'
-		elif self.testManual:
-			return 'MANUAL'
-		else:
-			return 'NONE'
-
-	def getExports(self, aBuildPlatform, aType="PRJ_EXPORTS"):
-		exportList = []
-
-		for exportLine in self.__getSection(aBuildPlatform, aType):
-
-			if not re.match(r'\S+', exportLine):
-				continue
-
-			try:
-				exportList.append(Export(exportLine.getFilename(), exportLine, aType))
-			except ValueError,e:
-				self.log.Error(str(e))
-
-		return exportList
-
-	def getTestExports(self, aBuildPlatform):
-		return self.getExports(aBuildPlatform, "PRJ_TESTEXPORTS")
-
-	def getExtensions(self, aBuildPlatform, aType="PRJ_EXTENSIONS"):
-		extensionObjects = []
-		start = ""
-		options = []
-
-		for extensionLine in self.__getSection(aBuildPlatform, aType):
-			if (re.search(r'^\s*START ',extensionLine, re.I)):
-				start = extensionLine
-			elif re.search(r'^\s*END\s*$',extensionLine, re.I):
-				extensionObjects.append(Extension(self.filename, start, options, aBuildPlatform, self.__Raptor))
-				start = ""
-				options = []
-			elif re.search(r'^\s*$',extensionLine, re.I):
-				continue
-			elif start:
-				options.append(extensionLine)
-
-		return extensionObjects
-
-	def getTestExtensions(self, aBuildPlatform):
-		return self.getExtensions(aBuildPlatform, "PRJ_TESTEXTENSIONS")
-
-	def __getSection(self, aBuildPlatform, aSection):
-
-		activeSection = False
-		sectionContent = []
-		lineContent = re.split(r'\n', self.getContent(aBuildPlatform));
-
-		currentBldInfFile = self.filename
-		currentLineNumber = 0
-
-		for line in lineContent:
-			if line.startswith("#"):
-				commentDetail = getPreProcessorCommentDetail(line)
-				currentBldInfFile = commentDetail[0]
-				currentLineNumber = commentDetail[1]-1
-				continue
-
-			currentLineNumber += 1
-
-			if not re.match(r'.*\S+', line):
-				continue
-			elif re.match(r'\s*' + aSection + r'\s*$', line, re.I):
-				activeSection = True
-			elif re.match(r'\s*PRJ_\w+\s*$', line, re.I):
-				activeSection = False
-			elif activeSection:
-				sectionContent.append(PreProcessedLine(line, currentBldInfFile, currentLineNumber))
-
-		return sectionContent
-
-	@staticmethod
-	def outputPathFragment(bldinfpath):
-		"""Return a relative path that uniquely identifies this bldinf file
-		   whilst being short so that it can be appended to epoc32/build.
-		   The  build product of a particular bld.inf may be placed in here.
-		   This affects its TEMs and its MMPs"""
-
-		absroot_str = os.path.abspath(str(bldinfpath)).lower().replace("\\","/")
-
-		uniqueid = hashlib.md5()
-		uniqueid.update(absroot_str)
-
-		specnamecomponents = (re.sub("^[A-Za-z]:", "", absroot_str)).split('/') # split, removing any drive identifier (if present)
-
-		pathlist=[]
-		while len(specnamecomponents) > 0:
-			top = specnamecomponents.pop()
-			if top.endswith('.inf'):
-				continue
-			elif top == 'group':
-				continue
-			else:
-				pathlist = [top]
-				break
-
-		pathlist.append("c_"+uniqueid.hexdigest()[:16])
-		return "/".join(pathlist)
-
-	def outputpath(self, platform):
-		""" The full path where product from this bldinf is created."""
-		return str(platform['SBS_BUILD_DIR']) + "/" + BldInfFile.outputPathFragment(self.filename)
-
-	def depspath(self, platform):
-	   """ Where does dependency information go relative to platform's SBS_BUILD_DIR?
-	       Subclasses should redefine this
-	   """
-	   return self.outputpath(platform) + "/bldinf." + platform['key_md5'] + ".d"
-
-
-
-class MMPRaptorBackend(MMPBackend):
-	"""A parser "backend" for the MMP language
-
-	This is used to map recognised MMP syntax onto a buildspec """
-
-	# Support priorities, with case-fixed mappings for use
-	epoc32priorities = {
-		'low':'Low',
-		'background':'Background',
-		'foreground':'Foreground',
-		'high':'High',
-		'windowserver':'WindowServer',
-		'fileserver':'FileServer',
-		'realtimeserver':'RealTimeServer',
-		'supervisor':'SuperVisor'
-		}
-
-	# Known capability flags with associated bitwise operations
-	supportedCapabilities = {
-		'tcb':(1<<0),
-		'commdd':(1<<1),
-		'powermgmt':(1<<2),
-		'multimediadd':(1<<3),
-		'readdevicedata':(1<<4),
-		'writedevicedata':(1<<5),
-		'drm':(1<<6),
-		'trustedui':(1<<7),
-		'protserv':(1<<8),
-		'diskadmin':(1<<9),
-		'networkcontrol':(1<<10),
-		'allfiles':(1<<11),
-		'swevent':(1<<12),
-		'networkservices':(1<<13),
-		'localservices':(1<<14),
-		'readuserdata':(1<<15),
-		'writeuserdata':(1<<16),
-		'location':(1<<17),
-		'surroundingsdd':(1<<18),
-		'userenvironment':(1<<19),
-	# Old capability names have zero value
-		'root':0,
-		'mediadd':0,
-		'readsystemdata':0,
-		'writesystemdata':0,
-		'sounddd':0,
-		'uidd':0,
-		'killanyprocess':0,
-		'devman':0,
-		'phonenetwork':0,
-		'localnetwork':0
-	  	}
-
-	library_re = re.compile(r"^(?P<name>[^{]+?)(?P<version>{(?P<major>[0-9]+)\.(?P<minor>[0-9]+)})?(\.(lib|dso))?$",re.I)
-
-
-	def __init__(self, aRaptor, aMmpfilename, aBldInfFilename):
-		super(MMPRaptorBackend,self).__init__()
-		self.platformblock = None
-		self.__Raptor = aRaptor
-		self.BuildVariant = raptor_data.Variant()
-		self.ResourceVariants = []
-		self.BitmapVariants = []
-		self.StringTableVariants = []
-		self.__bldInfFilename = aBldInfFilename
-		self.__targettype = "UNKNOWN"
-		self.__currentMmpFile = aMmpfilename
-		self.__defFileRoot = self.__currentMmpFile
-		self.__currentLineNumber = 0
-		self.__sourcepath = raptor_utilities.resolveSymbianPath(self.__currentMmpFile, "")
-		self.__userinclude = ""
-		self.__systeminclude = ""
-		self.__bitmapSourcepath = self.__sourcepath
-		self.__current_resource = ""
-		self.__capabilities = []
-		self.__resourceFiles = []
-		self.__pageConflict = []
-		self.__debuggable = ""
-		self.sources = []
-
-		self.__TARGET = ""
-		self.__TARGETEXT = ""
-		self.deffile = ""
-		self.__LINKAS = ""
-		self.nostrictdef = False
-		self.featureVariant = False
-
-		self.__currentResourceVariant = None
-		self.__currentStringTableVariant = None
-		self.__explicitversion = False
-		self.__versionhex = ""
-
-		# "ALL" capability calculated based on the total capabilities currently supported
-		allCapabilities = 0
-		for supportedCapability in MMPRaptorBackend.supportedCapabilities.keys():
-			allCapabilities = allCapabilities | MMPRaptorBackend.supportedCapabilities[supportedCapability]
-		MMPRaptorBackend.supportedCapabilities['all'] = allCapabilities
-
-	# Permit unit-testing output without a Raptor context
-	def __debug(self, format, *extras):
-		if (self.__Raptor):
-			self.__Raptor.Debug(format, *extras)
-
-	def __warn(self, format, *extras):
-		if (self.__Raptor):
-			self.__Raptor.Warn(format, *extras)
-
-	def doPreProcessorComment(self,s,loc,toks):
-		commentDetail = getPreProcessorCommentDetail(toks[0])
-		self.__currentMmpFile = commentDetail[0].GetLocalString()
-		self.__currentLineNumber = commentDetail[1]
-		self.__debug("Current file %s, line number %s\n"  % (self.__currentMmpFile,str(self.__currentLineNumber)))
-		return "OK"
-
-	def doBlankLine(self,s,loc,toks):
-		self.__currentLineNumber += 1
-
-	def doStartPlatform(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		self.__debug( "Start Platform block "+toks[0])
-		self.platformblock = toks[0]
-		return "OK"
-
-	def doEndPlatform(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		self.__debug( "Finalise platform " + self.platformblock)
-		return "OK"
-
-	def doSetSwitch(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		prefix=""
-		varname = toks[0].upper()
-
-		# A bright spark made the optionname the same as
-		# the env variable. One will override the other if we pass this
-		# on to make.  Add a prefix to prevent the clash.
-		if varname=='ARMINC':
-			prefix="SET_"
-			self.__debug( "Set switch "+toks[0]+" ON")
-			self.BuildVariant.AddOperation(raptor_data.Set(prefix+varname, "1"))
-
-		elif varname=='NOSTRICTDEF':
-			self.nostrictdef = True
-			self.__debug( "Set switch "+toks[0]+" ON")
-			self.BuildVariant.AddOperation(raptor_data.Set(prefix+varname, "1"))
-
-		elif varname == 'PAGED':
-			self.BuildVariant.AddOperation(raptor_data.Set(varname, "1"))
-			self.__debug( "Set switch PAGE ON")
-			self.BuildVariant.AddOperation(raptor_data.Set("PAGEDCODE_OPTION", "paged"))
-			self.__debug( "Set switch PAGEDCODE ON")
-			self.BuildVariant.AddOperation(raptor_data.Set("PAGEDDATA_OPTION", "paged"))
-			self.__debug( "Set data PAGEDDATA ON")
-			self.__pageConflict.append("PAGEDCODE")
-			self.__pageConflict.append("PAGEDDATA")
-
-		elif varname == 'UNPAGED':
-			self.BuildVariant.AddOperation(raptor_data.Set("PAGED", "0"))
-			self.__debug( "Set switch PAGED OFF")
-			self.BuildVariant.AddOperation(raptor_data.Set("PAGEDCODE_OPTION", "unpaged"))
-			self.__debug( "Set switch PAGEDCODE OFF")
-			self.BuildVariant.AddOperation(raptor_data.Set("PAGEDDATA_OPTION", "unpaged"))
-			self.__debug( "Set data PAGEDDATA OFF")
-			self.__pageConflict.append("UNPAGEDCODE")
-			self.__pageConflict.append("UNPAGEDDATA")
-
-		elif varname == 'PAGEDCODE':
-			self.BuildVariant.AddOperation(raptor_data.Set("PAGEDCODE_OPTION", "paged"))
-			self.__debug( "Set switch " + varname + " ON")
-			self.__pageConflict.append(varname)
-
-		elif varname == 'PAGEDDATA':
-			self.BuildVariant.AddOperation(raptor_data.Set("PAGEDDATA_OPTION", "paged"))
-			self.__debug( "Set switch " + varname + " ON")
-			self.__pageConflict.append(varname)
-
-		elif varname == 'UNPAGEDCODE':
-			self.BuildVariant.AddOperation(raptor_data.Set("PAGEDCODE_OPTION", "unpaged"))
-			self.__debug( "Set switch " + varname + " ON")
-			self.__pageConflict.append(varname)
-		elif varname == 'UNPAGEDDATA':
-			self.BuildVariant.AddOperation(raptor_data.Set("PAGEDDATA_OPTION", "unpaged"))
-			self.__debug( "Set switch " + varname + " ON")
-			self.__pageConflict.append(varname)
-
-		elif varname == 'NOLINKTIMECODEGENERATION':
-			self.BuildVariant.AddOperation(raptor_data.Set("LTCG",""))
-			self.__debug( "Set switch " + varname + " OFF")
-		elif varname == 'NOMULTIFILECOMPILATION':
-			self.BuildVariant.AddOperation(raptor_data.Set("MULTIFILE_ENABLED",""))
-			self.__debug( "Set switch " + varname + " OFF")
-
-		elif varname == 'DEBUGGABLE':
-			if self.__debuggable != "udeb":
-				self.__debuggable = "udeb urel"
-			else:
-				self.__Raptor.Warn("DEBUGGABLE keyword ignored as DEBUGGABLE_UDEBONLY is already specified")
-		elif varname == 'DEBUGGABLE_UDEBONLY':
-			if self.__debuggable != "":
-				self.__Raptor.Warn("DEBUGGABLE keyword has no effect as DEBUGGABLE or DEBUGGABLE_UDEBONLY is already set")
-			self.__debuggable = "udeb"
-		elif varname == 'FEATUREVARIANT':
-			self.BuildVariant.AddOperation(raptor_data.Set(varname,"1"))
-			self.featureVariant = True
-		else:
-			self.__debug( "Set switch "+toks[0]+" ON")
-			self.BuildVariant.AddOperation(raptor_data.Set(prefix+varname, "1"))
-
-		return "OK"
-
-	def doAssignment(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		varname = toks[0].upper()
-		if varname=='TARGET':
-			(self.__TARGET, self.__TARGETEXT) = os.path.splitext(toks[1])
-			self.__TARGETEXT = self.__TARGETEXT.lstrip('.')
-
-			self.BuildVariant.AddOperation(raptor_data.Set("REQUESTEDTARGETEXT", self.__TARGETEXT.lower()))
-
-			lowercase_TARGET = self.__TARGET.lower()
-			self.__debug("Set "+toks[0]+" to " + lowercase_TARGET)
-			self.__debug("Set REQUESTEDTARGETEXT to " + self.__TARGETEXT.lower())
-
-			self.BuildVariant.AddOperation(raptor_data.Set("TARGET", self.__TARGET))
-			self.BuildVariant.AddOperation(raptor_data.Set("TARGET_lower", lowercase_TARGET))
-			if  lowercase_TARGET !=  self.__TARGET:
-				self.__debug("TARGET is not lowercase: '%s' - might cause BC problems." % self.__TARGET)
-		elif varname=='TARGETTYPE':
-			self.__debug("Set "+toks[0]+" to " + str(toks[1]))
-			self.__targettype=toks[1]
-			if  self.__targettype.lower() == "none":
-				self.BuildVariant.AddOperation(raptor_data.Set("TARGET", ""))
-				self.BuildVariant.AddOperation(raptor_data.Set("TARGET_lower",""))
-				self.BuildVariant.AddOperation(raptor_data.Set("REQUESTEDTARGETEXT", ""))
-			self.BuildVariant.AddOperation(raptor_data.Set(varname,toks[1].lower()))
-
-		elif varname=='TARGETPATH':
-			value = toks[1].lower().replace('\\','/')
-			self.__debug("Set "+varname+" to " + value)
-			self.BuildVariant.AddOperation(raptor_data.Set(varname, value))
-
-		elif varname=='OPTION' or varname=='LINKEROPTION':
-			self.__debug("Set "+toks[1]+varname+" to " + str(toks[2]))
-			self.BuildVariant.AddOperation(raptor_data.Append(varname+"_"+toks[1].upper()," ".join(toks[2])))
-
-			# Warn about OPTION ARMASM
-			if "armasm" in toks[1].lower():
-				self.__Raptor.Warn(varname+" ARMASM has no effect (use OPTION ARMCC).")
-
-		elif varname=='OPTION_REPLACE':
-			# Warn about OPTION_REPLACE ARMASM
-			if "armasm" in toks[1].lower():
-				self.__Raptor.Warn("OPTION_REPLACE ARMASM has no effect (use OPTION_REPLACE ARMCC).")
-			else:
-				args = " ".join(toks[2])
-
-				searchReplacePairs = self.resolveOptionReplace(args)
-
-				for searchReplacePair in searchReplacePairs:
-					self.__debug("Append %s to OPTION_REPLACE_%s", searchReplacePair, toks[1].upper())
-					self.BuildVariant.AddOperation(raptor_data.Append(varname+"_"+toks[1].upper(),searchReplacePair))
-
-		elif varname=='SYSTEMINCLUDE' or varname=='USERINCLUDE':
-			for path in toks[1]:
-				resolved = raptor_utilities.resolveSymbianPath(self.__currentMmpFile, path)
-				self.BuildVariant.AddOperation(raptor_data.Append(varname,resolved))
-
-				if varname=='SYSTEMINCLUDE':
-					self.__systeminclude += ' ' + resolved
-					self.__debug("  %s = %s",varname, self.__systeminclude)
-				else:
-					self.__userinclude += ' ' + resolved
-					self.__debug("  %s = %s",varname, self.__userinclude)
-
-				self.__debug("Appending %s to %s",resolved, varname)
-
-			self.__systeminclude = self.__systeminclude.strip()
-			self.__systeminclude = self.__systeminclude.rstrip('\/')
-			self.__userinclude = self.__userinclude.strip()
-			self.__userinclude = self.__userinclude.rstrip('\/')
-
-		elif varname=='EXPORTLIBRARY':
-			# Remove extension from the EXPORTLIBRARY name
-			libName = toks[1].rsplit(".", 1)[0]
-			self.__debug("Set "+varname+" to " + libName)
-			self.BuildVariant.AddOperation(raptor_data.Set(varname,"".join(libName)))
-
-		elif varname=='CAPABILITY':
-			for cap in toks[1]:
-				self.BuildVariant.AddOperation(raptor_data.Append(varname,cap," "))
-				self.__debug("Setting  "+toks[0]+": " + cap)
-				self.__capabilities.append(cap.lower())
-		elif varname=='DEFFILE':
-			self.__defFileRoot = self.__currentMmpFile
-			self.deffile = toks[1]
-		elif varname=='LINKAS':
-			self.__debug("Set "+toks[0]+"  OPTION to " + str(toks[1]))
-			self.__LINKAS = toks[1]
-			self.BuildVariant.AddOperation(raptor_data.Set(varname, toks[1]))
-		elif varname=='SECUREID' or varname=='VENDORID':
-			hexoutput = MMPRaptorBackend.canonicalUID(toks[1])
-			self.__debug("Set "+toks[0]+"  OPTION to " + hexoutput)
-			self.BuildVariant.AddOperation(raptor_data.Set(varname, hexoutput))
-		elif varname=='VERSION':
-			if toks[-1] == "EXPLICIT":
-				self.__explicitversion = True
-				self.BuildVariant.AddOperation(raptor_data.Set("EXPLICITVERSION", "1"))
-
-			vm = re.match(r'^(\d+)(\.(\d+))?$', toks[1])
-			if vm is not None:
-				version = vm.groups()
-				# the major version number
-				major = int(version[0],10)
-
-				# add in the minor number
-				minor = 0
-				if len(version) >  1:
-					minor = int(version[2],10)
-
-				self.__versionhex = "%04x%04x" % (major, minor)
-				self.BuildVariant.AddOperation(raptor_data.Set(varname, "%d.%d" %(major, minor)))
-				self.BuildVariant.AddOperation(raptor_data.Set(varname+"HEX", self.__versionhex))
-				self.__debug("Set "+toks[0]+"  OPTION to " + toks[1])
-				self.__debug("Set "+toks[0]+"HEX OPTION to " + "%04x%04x" % (major,minor))
-
-			else:
-				self.__Raptor.Warn("Invalid version supplied to VERSION (%s), using default value" % toks[1])
-
-		elif varname=='EPOCHEAPSIZE':
-			# Standardise on sending hex numbers to the FLMS.
-
-			if toks[1].lower().startswith('0x'):
-				min = long(toks[1],16)
-			else:
-				min = long(toks[1],10)
-
-			if toks[2].lower().startswith('0x'):
-				max = long(toks[2],16)
-			else:
-				max = long(toks[2],10)
-
-			self.BuildVariant.AddOperation(raptor_data.Set(varname+"MIN", "%x" % min))
-			self.__debug("Set "+varname+"MIN  OPTION to '%x' (hex)" % min )
-			self.BuildVariant.AddOperation(raptor_data.Set(varname+"MAX", "%x" % max))
-			self.__debug("Set "+varname+"MAX  OPTION to '%x' (hex)" % max )
-
-			# Some toolchains require decimal versions of the min/max values, converted to KB and
-			# rounded up to the next 1KB boundary
-			min_dec_kb = (int(min) + 1023) / 1024
-			max_dec_kb = (int(max) + 1023) / 1024
-			self.BuildVariant.AddOperation(raptor_data.Set(varname+"MIN_DEC_KB", "%d" % min_dec_kb))
-			self.__debug("Set "+varname+"MIN  OPTION KB to '%d' (dec)" % min_dec_kb )
-			self.BuildVariant.AddOperation(raptor_data.Set(varname+"MAX_DEC_KB", "%d" % max_dec_kb))
-			self.__debug("Set "+varname+"MAX  OPTION KB to '%d' (dec)" % max_dec_kb )
-
-		elif varname=='EPOCSTACKSIZE':
-			if toks[1].lower().startswith('0x'):
-				stack = long(toks[1],16)
-			else:
-				stack = long(toks[1],10)
-			self.BuildVariant.AddOperation(raptor_data.Set(varname, "%x" % stack))
-			self.__debug("Set "+varname+"  OPTION to '%x' (hex)" % stack  )
-		elif varname=='EPOCPROCESSPRIORITY':
-			# low, background, foreground, high, windowserver, fileserver, realtimeserver or supervisor
-			# These are case insensitive in metadata entries, but must be mapped to a static case pattern for use
-			prio = toks[1].lower()
-
-			# NOTE: Original validation here didn't actually work.  This has been corrected to provide an error, but probably needs re-examination.
-			if not MMPRaptorBackend.epoc32priorities.has_key(prio):
-				self.__Raptor.Error("Priority setting '%s' is not a valid priority - should be one of %s.", prio, MMPRaptorBackend.epoc32priorities.values())
-			else:
-				self.__debug("Set "+toks[0]+" to " +  MMPRaptorBackend.epoc32priorities[prio])
-				self.BuildVariant.AddOperation(raptor_data.Set(varname,MMPRaptorBackend.epoc32priorities[prio]))
-		elif varname=='ROMTARGET' or varname=='RAMTARGET':
-			if len(toks) == 1:
-				self.__debug("Set "+toks[0]+" to <none>" )
-				self.BuildVariant.AddOperation(raptor_data.Set(varname,"<none>"))
-			else:
-				toks1 = str(toks[1]).replace("\\","/")
-				if toks1.find(","):
-					toks1 = re.sub("[,'\[\]]", "", toks1).replace("//","/")
-				self.__debug("Set "+toks[0]+" to " + toks1)
-				self.BuildVariant.AddOperation(raptor_data.Set(varname,toks1))
-
-		else:
-			self.__debug("Set "+toks[0]+" to " + str(toks[1]))
-			self.BuildVariant.AddOperation(raptor_data.Set(varname,"".join(toks[1])))
-
-			if varname=='LINKAS':
-				self.__LINKAS = toks[1]
-
-		return "OK"
-
-	def doAppend(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		"""MMP command
-		"""
-		name=toks[0].upper()
-		if len(toks) == 1:
-			# list can be empty e.g. MACRO _FRED_ when fred it defined in the HRH
-			# causes us to see just "MACRO" in the input - it is valid to ignore this
-			self.__debug("Empty append list for " + name)
-			return "OK"
-		self.__debug("Append to "+name+" the values: " +str(toks[1]))
-
-		if name=='MACRO':
-			name='MMPDEFS'
-		elif name=='LANG':
-			# don't break the environment variable
-			name='LANGUAGES'
-
-		for item in toks[1]:
-			if name=='MMPDEFS':
-				# Unquote any macros since the FLM does it anyhow
-				if item.startswith('"') and item.endswith('"') \
-				or item.startswith("'") and item.endswith("'"):
-					item = item.strip("'\"")
-			if name=='LIBRARY' or name=='DEBUGLIBRARY':
-				im = MMPRaptorBackend.library_re.match(item)
-				if not im:
-					self.__error("LIBRARY: %s Seems to have an invalid name.\nExpected xxxx.lib or xxxx.dso\n where xxxx might be\n\tname or \n\tname(n,m) where n is a major version number and m is a minor version number\n" %item)
-				d = im.groupdict()
-
-				item = d['name']
-				if d['version'] is not None:
-					item += "{%04x%04x}" % (int(d['major']), int(d['minor']))
-				item += ".dso"
-			elif name=='STATICLIBRARY':
-				# the FLM will decide on the ending appropriate to the platform
-				item = re.sub(r"^(.*)\.[Ll][Ii][Bb]$",r"\1", item)
-			elif name=="LANGUAGES":
-				item = item.lower()
-			elif (name=="WIN32_LIBRARY" and (item.startswith(".") or re.search(r'[\\|/]',item))) \
-				or (name=="WIN32_RESOURCE"):
-				# Relatively pathed win32 libraries, and all win32 resources, are resolved in relation
-				# to the wrapper bld.inf file in which their .mmp file is specified.  This equates to
-				# the current working directory in ABLD operation.
-				item = raptor_utilities.resolveSymbianPath(self.__bldInfFilename, item)
-				
-			self.BuildVariant.AddOperation(raptor_data.Append(name,item," "))
-			
-			# maintain a debug library list, the same as LIBRARY but with DEBUGLIBRARY values
-			# appended as they are encountered
-			if name=='LIBRARY' or name=='DEBUGLIBRARY':
-				self.BuildVariant.AddOperation(raptor_data.Append("LIBRARY_DEBUG",item," "))			
-
-		return "OK"
-
-	def canonicalUID(number):
-		""" convert a UID string into an 8 digit hexadecimal string without leading 0x """
-		if number.lower().startswith("0x"):
-			n = int(number,16)
-		else:
-			n = int(number,10)
-
-		return "%08x" % n
-
-	canonicalUID = staticmethod(canonicalUID)
-
-	def doUIDAssignment(self,s,loc,toks):
-		"""A single UID command results in a number of spec variables"""
-		self.__currentLineNumber += 1
-
-		hexoutput = MMPRaptorBackend.canonicalUID(toks[1][0])
-		self.__debug( "Set UID2 to %s" % hexoutput )
-		self.BuildVariant.AddOperation(raptor_data.Set("UID2", hexoutput))
-
-		if len(toks[1]) > 1:
-			hexoutput = MMPRaptorBackend.canonicalUID(toks[1][1])
-			self.__debug( "Set UID3 to %s" % hexoutput)
-			self.BuildVariant.AddOperation(raptor_data.Set("UID3", hexoutput))
-
-		self.__debug( "done set UID")
-		return "OK"
-
-	def doSourcePathAssignment(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		self.__sourcepath = raptor_utilities.resolveSymbianPath(self.__currentMmpFile, toks[1])
-		self.__debug( "Remembering self.sourcepath state:  "+str(toks[0])+" is now " + self.__sourcepath)
-		self.__debug("selfcurrentMmpFile: " + self.__currentMmpFile)
-		return "OK"
-
-
-	def doSourceAssignment(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		self.__debug( "Setting "+toks[0]+" to " + str(toks[1]))
-		for file in toks[1]:
-			# file is always relative to sourcepath but some MMP files
-			# have items that begin with a slash...
-			file = file.lstrip("/")
-			source = generic_path.Join(self.__sourcepath, file)
-
-			# If the SOURCEPATH itself begins with a '/', then dont look up the caseless version, since
-			# we don't know at this time what $(EPOCROOT) will evaluate to.
-			if source.GetLocalString().startswith('$(EPOCROOT)'):
-				self.sources.append(str(source))	
-				self.__debug("Append SOURCE " + str(source))
-
-			else:
-				foundsource = source.FindCaseless()
-				if foundsource == None:
-					# Hope that the file will be generated later
-					self.__debug("Sourcefile not found: %s" % source)
-					foundsource = source
-
-				self.sources.append(str(foundsource))	
-				self.__debug("Append SOURCE " + str(foundsource))
-
-
-		self.__debug("		sourcepath: " + self.__sourcepath)
-		return "OK"
-
-	# Resource
-
-	def doOldResourceAssignment(self,s,loc,toks):
-		# Technically deprecated, but still used, so...
-		self.__currentLineNumber += 1
-		self.__debug("Processing old-style "+toks[0]+" "+str(toks[1]))
-
-		sysRes = (toks[0].lower() == "systemresource")
-
-		for rss in toks[1]:
-			variant = raptor_data.Variant()
-
-			source = generic_path.Join(self.__sourcepath, rss)
-			variant.AddOperation(raptor_data.Set("SOURCE", str(source)))
-			self.__resourceFiles.append(str(source))
-
-			target = source.File().rsplit(".", 1)[0]	# remove the extension
-			variant.AddOperation(raptor_data.Set("TARGET", target))
-			variant.AddOperation(raptor_data.Set("TARGET_lower", target.lower()))
-
-			header = target.lower() + ".rsg"			# filename policy
-			variant.AddOperation(raptor_data.Set("HEADER", header))
-
-			if sysRes:
-				dsrtp = self.getDefaultSystemResourceTargetPath()
-				variant.AddOperation(raptor_data.Set("TARGETPATH", dsrtp))
-
-			self.ResourceVariants.append(variant)
-
-		return "OK"
-
-	def getDefaultSystemResourceTargetPath(self):
-		# the default systemresource TARGETPATH value should come from the
-		# configuration rather than being hard-coded here. Then again, this
-		# should really be deprecated away into oblivion...
-		return "system/data"
-
-
-	def getDefaultResourceTargetPath(self, targettype):
-		# the different default TARGETPATH values should come from the
-		# configuration rather than being hard-coded here.
-		if targettype == "plugin":
-			return "resource/plugins"
-		if targettype == "pdl":
-			return "resource/printers"
-		return ""
-
-	def resolveOptionReplace(self, content):
-		"""
-		Constructs search/replace pairs based on .mmp OPTION_REPLACE entries for use on tool command lines
-		within FLMS.
-
-		Depending on what's supplied to OPTION_REPLACE <TOOL>, the core part of the <TOOL> command line
-		in the relevant FLM will have search and replace actions performed on it post-expansion (but pre-
-		any OPTION <TOOL> additions).
-
-		In terms of logic, we try to follow what ABLD does, as the current behaviour is undocumented.
-		What happens is a little inconsistent, and best described by some generic examples:
-
-			OPTION_REPLACE TOOL existing_option replacement_value
-
-				Replace all instances of "option existing_value" with "option replacement_value"
-
-			OPTION_REPLACE TOOL existing_option replacement_option
-
-				Replace all instances of "existing_option" with "replacement_option".
-
-			If "existing_option" is present in isolation then a removal is performed.
-
-		Any values encountered that don't follow an option are ignored.
-		Options are identified as being prefixed with either '-' or '--'.
-
-		The front-end processes each OPTION_REPLACE entry and then appends one or more search/replace pairs
-		to an OPTION_REPLACE_<TOOL> variable in the following format:
-
-		     search<->replace
-		"""
-		# Note that, for compatibility reasons, the following is mostly a port to Python of the corresponding
-		# ABLD Perl, and hence maintains ABLD's idiosyncrasies in what it achieves
-
-		searchReplacePairs = []
-		matches = re.findall("-{1,2}\S+\s*(?!-)\S*",content)
-
-		if matches:
-			# reverse so we can process as a stack whilst retaining original order
-			matches.reverse()
-
-			while (len(matches)):
-				match = matches.pop()
-
-				standaloneMatch = re.match('^(?P<option>\S+)\s+(?P<value>\S+)$', match)
-
-				if (standaloneMatch):
-					# Option listed standalone with a replacement value
-					# Example:
-					# 	OPTION_REPLACE ARMCC --cpu 6
-					# Intention:
-					# 	Replace instances of  "--cpu <something>" with "--cpu 6"
-
-					# Substitute any existing "option <existing_value>" instances with a single word
-					# "@@<existing_value>" for later replacement
-					searchReplacePairs.append('%s <->@@' % standaloneMatch.group('option'))
-
-					# Replace "@@<existing_value>" entries from above with "option <new_value>" entries
-					# A pattern substitution is used to cover pre-existing values
-					searchReplacePairs.append('@@%%<->%s %s' % (standaloneMatch.group('option'), standaloneMatch.group('value')))
-				else:
-					# Options specified in search/replace pairs with optional values
-					# Example:
-					#	OPTION_REPLACE ARMCC --O2 --O3
-					# Intention:
-					#	Replace instances of "--O2" with "--O3"
-
-					# At this point we will be looking at just the search option - there may or may not
-					# be a replacement to consider
-					search = match
-					replace = ""
-					if len(matches):
-						replace = matches.pop()
-					
-					searchReplacePairs.append('%s<->%s' % (search, replace))
-
-			# Replace spaces to maintain word-based grouping in downstream makefile lists
-			for i in range(0,len(searchReplacePairs)):
-				searchReplacePairs[i] = searchReplacePairs[i].replace(' ','%20')
-
-		return searchReplacePairs
-
-	def doStartResource(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		self.__debug("Start RESOURCE "+toks[1])
-
-		self.__current_resource = generic_path.Path(self.__sourcepath, toks[1])
-		self.__current_resource = str(self.__current_resource)
-
-		self.__debug("sourcepath: " + self.__sourcepath)
-		self.__debug("self.__current_resource source: " + toks[1])
-		self.__debug("adjusted self.__current_resource source=" + self.__current_resource)
-
-		self.__currentResourceVariant = raptor_data.Variant()
-		self.__currentResourceVariant.AddOperation(raptor_data.Set("SOURCE", self.__current_resource))
-		self.__resourceFiles.append(self.__current_resource)
-
-		# The target name is the basename of the resource without the extension
-		# e.g. "/fred/129ab34f.rss" would have a target name of "129ab34f"
-		target = self.__current_resource.rsplit("/",1)[-1]
-		target = target.rsplit(".",1)[0]
-		self.__currentResourceVariant.AddOperation(raptor_data.Set("TARGET", target))
-		self.__currentResourceVariant.AddOperation(raptor_data.Set("TARGET_lower", target.lower()))
-		self.__headerspecified = False
-		self.__headeronlyspecified = False
-		self.__current_resource_header = target.lower() + ".rsg"
-
-		return "OK"
-
-	def doResourceAssignment(self,s,loc,toks):
-		""" Assign variables for resource files """
-		self.__currentLineNumber += 1
-		varname = toks[0].upper() # the mmp keyword
-		varvalue = "".join(toks[1])
-
-		# Get rid of any .rsc extension because the build system
-		# needs to have it stripped off to calculate other names
-		# for other purposes and # we aren't going to make it
-		# optional anyhow.
-		if varname == "TARGET":
-			target_withext = varvalue.rsplit("/\\",1)[-1]
-			target = target_withext.rsplit(".",1)[0]
-			self.__current_resource_header = target.lower() + ".rsg"
-			self.__currentResourceVariant.AddOperation(raptor_data.Set("TARGET_lower", target.lower()))
-			self.__debug("Set resource "+varname+" to " + target)
-			self.__currentResourceVariant.AddOperation(raptor_data.Set(varname,target))
-		if varname == "TARGETPATH":
-			varvalue=varvalue.replace('\\','/')
-			self.__debug("Set resource "+varname+" to " + varvalue)
-			self.__currentResourceVariant.AddOperation(raptor_data.Set(varname,varvalue))
-		else:
-			self.__debug("Set resource "+varname+" to " + varvalue)
-			self.__currentResourceVariant.AddOperation(raptor_data.Set(varname,varvalue))
-		return "OK"
-
-	def doResourceAppend(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		self.__debug("Append resource to "+toks[0]+" the values: " +str(toks[1]))
-		varname = toks[0].upper()
-
-		# we cannot use LANG as it interferes with the environment
-		if varname == "LANG":
-			varname = "LANGUAGES"
-
-		for item in toks[1]:
-			if varname == "LANGUAGES":
-				item = item.lower()
-			self.__currentResourceVariant.AddOperation(raptor_data.Append(varname,item))
-		return "OK"
-
-	def doResourceSetSwitch(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		name = toks[0].upper()
-
-		if name == "HEADER":
-			self.__headerspecified = True
-
-		elif name == "HEADERONLY":
-			self.__headeronlyspecified = True
-
-		else:
-			value = "1"
-			self.__debug( "Set resource switch " + name + " " + value)
-			self.__currentResourceVariant.AddOperation(raptor_data.Set(name, value))
-
-		return "OK"
-
-	def doEndResource(self,s,loc,toks):
-		self.__currentLineNumber += 1
-
-		# Header name can change, depening if there was a TARGET defined or not, so it must be appended at the end
-		if self.__headerspecified:
-			self.__debug("Set resource switch HEADER " + self.__current_resource_header)
-			self.__currentResourceVariant.AddOperation(raptor_data.Set("HEADER", self.__current_resource_header))
-
-		if self.__headeronlyspecified:
-			self.__debug("Set resource switch HEADERONLY " + self.__current_resource_header)
-			self.__currentResourceVariant.AddOperation(raptor_data.Set("HEADER", self.__current_resource_header))
-			self.__currentResourceVariant.AddOperation(raptor_data.Set("HEADERONLY", "True"))
-
-		self.__debug("End RESOURCE")
-		self.ResourceVariants.append(self.__currentResourceVariant)
-		self.__currentResourceVariant = None
-		self.__current_resource = ""
-		return "OK"
-
-	# Bitmap
-
-	def doStartBitmap(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		self.__debug("Start BITMAP "+toks[1])
-
-		self.__currentBitmapVariant = raptor_data.Variant(toks[1].replace('.','_'))
-		# Use BMTARGET and BMTARGET_lower because that prevents
-		# confusion with the TARGET and TARGET_lower of our parent MMP
-		# when setting the OUTPUTPATH.  This in turn allows us to
-		# not get tripped up by multiple mbms being generated with
-		# the same name to the same directory.
-		self.__currentBitmapVariant.AddOperation(raptor_data.Set("BMTARGET", toks[1]))
-		self.__currentBitmapVariant.AddOperation(raptor_data.Set("BMTARGET_lower", toks[1].lower()))
-		self.__currentBitmapVariant.AddOperation(raptor_data.Set("SOURCE", ""))
-		return "OK"
-
-	def doBitmapAssignment(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		self.__debug("Set bitmap "+toks[0]+" to " + str(toks[1]))
-		name = toks[0].upper()
-		value = "".join(toks[1])
-		if name == "TARGETPATH":
-			value = value.replace('\\','/')
-
-		self.__currentBitmapVariant.AddOperation(raptor_data.Set(name,value))
-		return "OK"
-
-	def doBitmapSourcePathAssignment(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		self.__debug("Previous bitmap sourcepath:" + self.__bitmapSourcepath)
-		self.__bitmapSourcepath = raptor_utilities.resolveSymbianPath(self.__currentMmpFile, toks[1])
-		self.__debug("New bitmap sourcepath: " + self.__bitmapSourcepath)
-
-	def doBitmapSourceAssignment(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		self.__debug( "Setting "+toks[0]+" to " + str(toks[1]))
-		# The first "source" is the colour depth for all the others.
-		# The depth format is b[,m] where b is the bitmap depth and m is
-		# the mask depth.
-		# Valid values for b are: 1 2 4 8 c4 c8 c12 c16 c24 c32 c32a (?)
-		# Valid values for m are: 1 8 (any number?)
-		#
-		# If m is specified then the bitmaps are in pairs: b0 m0 b1 m1...
-		# If m is not specified then there are no masks, just bitmaps: b0 b1...
-		colordepth = toks[1][0].lower()
-		if "," in colordepth:
-			(bitmapdepth, maskdepth) = colordepth.split(",")
-		else:
-			bitmapdepth = colordepth
-			maskdepth = 0
-
-		sources=""
-		mask = False
-		for file in toks[1][1:]:
-			path = generic_path.Join(self.__bitmapSourcepath, file)
-			if sources:
-				sources += " "
-			if mask:
-				sources += "DEPTH=" + maskdepth + " FILE=" + str(path)
-			else:
-				sources += "DEPTH=" + bitmapdepth + " FILE=" + str(path)
-			if maskdepth:
-				mask = not mask
-		self.__debug("sources: " + sources)
-		self.__currentBitmapVariant.AddOperation(raptor_data.Append("SOURCE", sources))
-		return "OK"
-
-	def doBitmapSetSwitch(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		self.__debug( "Set bitmap switch "+toks[0]+" ON")
-		self.__currentBitmapVariant.AddOperation(raptor_data.Set(toks[0].upper(), "1"))
-		return "OK"
-
-	def doEndBitmap(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		self.__bitmapSourcepath = self.__sourcepath
-		self.BitmapVariants.append(self.__currentBitmapVariant)
-		self.__currentBitmapVariant = None
-		self.__debug("End BITMAP")
-		return "OK"
-
-	# Stringtable
-
-	def doStartStringTable(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		self.__debug( "Start STRINGTABLE "+toks[1])
-
-		specstringtable = generic_path.Join(self.__sourcepath, toks[1])
-		uniqname = specstringtable.File().replace('.','_') # corrected, filename only
-		source = str(specstringtable.FindCaseless())
-
-		self.__debug("sourcepath: " + self.__sourcepath)
-		self.__debug("stringtable: " + toks[1])
-		self.__debug("adjusted stringtable source=" + source)
-
-		self.__currentStringTableVariant = raptor_data.Variant(uniqname)
-		self.__currentStringTableVariant.AddOperation(raptor_data.Set("SOURCE", source))
-		self.__currentStringTableVariant.AddOperation(raptor_data.Set("EXPORTPATH", ""))
-		self.__stringtableExported = False
-
-		# The target name by default is the name of the stringtable without the extension
-		# e.g. the stringtable "/fred/http.st" would have a default target name of "http"
-		stringtable_withext = specstringtable.File()
-		self.__stringtable = stringtable_withext.rsplit(".",1)[0].lower()
-		self.__currentStringTableVariant.AddOperation(raptor_data.Set("TARGET", self.__stringtable))
-
-		self.__stringtableHeaderonlyspecified = False
-
-		return "OK"
-
-	def doStringTableAssignment(self,s,loc,toks):
-		""" Assign variables for stringtables """
-		self.__currentLineNumber += 1
-		varname = toks[0].upper() # the mmp keyword
-		varvalue = "".join(toks[1])
-
-		# Get rid of any .rsc extension because the build system
-		# needs to have it stripped off to calculate other names
-		# for other purposes and # we aren't going to make it
-		# optional anyhow.
-		if varname == "EXPORTPATH":
-			finalvalue = raptor_utilities.resolveSymbianPath(self.__currentMmpFile, varvalue)
-			self.__stringtableExported = True
-		else:
-			finalvalue = varvalue
-
-		self.__debug("Set stringtable "+varname+" to " + finalvalue)
-		self.__currentStringTableVariant.AddOperation(raptor_data.Set(varname,finalvalue))
-		return "OK"
-
-	def doStringTableSetSwitch(self,s,loc,toks):
-		self.__currentLineNumber += 1
-		if toks[0].upper()== "HEADERONLY":
-			self.__stringtableHeaderonlyspecified = True
-			self.__debug( "Set stringtable switch "+toks[0]+" ON")
-			self.__currentStringTableVariant.AddOperation(raptor_data.Set(toks[0].upper(), "1"))
-		return "OK"
-
-	def doEndStringTable(self,s,loc,toks):
-		self.__currentLineNumber += 1
-
-		if not self.__stringtableExported:
-			# There was no EXPORTPATH specified for this stringtable
-			# so for our other code to be able to reference it we
-			# must add the path of the generated location to the userinclude path
-
-			ipath = "$(OUTPUTPATH)"
-			self.BuildVariant.AddOperation(raptor_data.Append("USERINCLUDE",ipath))
-			self.__userinclude += ' ' + ipath
-			self.__debug("  USERINCLUDE = %s", self.__userinclude)
-			self.__userinclude.strip()
-
-		self.StringTableVariants.append(self.__currentStringTableVariant)
-		self.__currentStringTableVariant = None
-		self.__debug("End STRINGTABLE")
-		if not self.__stringtableHeaderonlyspecified:
-			# Have to assume that this is where the cpp file will be.  This has to be maintained
-			# in sync with the FLM's idea of where this file should be.  We need a better way.
-			# Interfaces also need outputs that allow other interfaces to refer to their outputs
-			# without having to "know" where they will be.
-			self.sources.append('$(OUTPUTPATH)/' + self.__stringtable + '.cpp')
-		return "OK"
-
-
-	def doUnknownStatement(self,s,loc,toks):
-		self.__warn("%s (%d) : Unrecognised Keyword %s", self.__currentMmpFile, self.__currentLineNumber, str(toks))
-		self.__currentLineNumber += 1
-		return "OK"
-
-
-	def doUnknownBlock(self,s,loc,toks):
-		self.__warn("%s (%d) : Unrecognised Block %s", self.__currentMmpFile, self.__currentLineNumber, str(toks))
-		self.__currentLineNumber += 1
-		return "OK"
-
-	def doDeprecated(self,s,loc,toks):
-		self.__debug( "Deprecated command " + str(toks))
-		self.__warn("%s (%d) : %s is deprecated .mmp file syntax", self.__currentMmpFile, self.__currentLineNumber, str(toks))
-		self.__currentLineNumber += 1
-		return "OK"
-
-	def doNothing(self):
-		self.__currentLineNumber += 1
-		return "OK"
-
-	def finalise(self, aBuildPlatform):
-		"""Post-processing of data that is only applicable in the context of a fully
-		processed .mmp file."""
-		resolvedDefFile = ""
-
-		if self.__TARGET:
-			defaultRootName = self.__TARGET
-			if self.__TARGETEXT!="":
-				defaultRootName += "." + self.__TARGETEXT
-
-			# NOTE: Changing default .def file name based on the LINKAS argument is actually
-			# a defect, but this follows the behaviour of the current build system.
-			if (self.__LINKAS):
-				defaultRootName = self.__LINKAS
-
-			resolvedDefFile = self.resolveDefFile(defaultRootName, aBuildPlatform)
-			self.__debug("Resolved def file:  %s" % resolvedDefFile )
-			# We need to store this resolved deffile location for the FREEZE target
-			self.BuildVariant.AddOperation(raptor_data.Set("RESOLVED_DEFFILE", resolvedDefFile))
-
-		# If a deffile is specified, an FLM will put in a dependency.
-		# If a deffile is specified then raptor_meta will guess a name but:
-		#	1) If the guess is wrong then the FLM will complain "no rule to make ..."
-		#	2) In some cases, e.g. plugin, 1) is not desirable as the presence of a def file
-		#		is not a necessity.  In these cases the FLM needs to know if DEFFILE
-		#		is a guess or not so it can decide if a dependency should be added.
-
-		# We check that the def file exists and that it is non-zero (incredible
-		# that this should be needed).
-
-		deffile_keyword="1"
-		if self.deffile == "":
-			# If the user didn't specify a deffile name then
-			# we must be guessing
-			# Let's check if our guess actually corresponds to a
-			# real file.  If it does then that confims the guess.
-			#  If there's no file then we still need to pass make the name
-			# so it can complain about there not being a DEF file
-			# for this particular target type and fail to build this target.
-
-			deffile_keyword=""
-			try:
-				findpath = generic_path.Path(resolvedDefFile)
-				foundfile = findpath.FindCaseless()
-
-				if foundfile == None:
-					raise IOError("file not found")
-
-				self.__debug("Found DEFFILE  " + foundfile.GetLocalString())
-				rfstat = os.stat(foundfile.GetLocalString())
-
-				mode = rfstat[stat.ST_MODE]
-				if mode != None and stat.S_ISREG(mode) and rfstat[stat.ST_SIZE] > 0:
-					resolvedDefFile = str(foundfile)
-				else:
-					resolvedDefFile=""
-			except Exception,e:
-				self.__debug("While Searching for an IMPLIED  DEFFILE: %s: %s" % (str(e),str(findpath)) )
-				resolvedDefFile=""
-		else:
-			if not resolvedDefFile == "":
-				try:
-					findpath = generic_path.Path(resolvedDefFile)
-					resolvedDefFile = str(findpath.FindCaseless())
-					if resolvedDefFile=="None":
-						raise IOError("file not found")
-				except Exception,e:
-					self.__warn("While Searching for a SPECIFIED DEFFILE: %s: %s" % (str(e),str(findpath)) )
-					resolvedDefFile=""
-			else:
-				self.__warn("DEFFILE KEYWORD used (%s) but def file not resolved" % (self.deffile) )
-
-
-		self.BuildVariant.AddOperation(raptor_data.Set("DEFFILE", resolvedDefFile))
-		self.__debug("Set DEFFILE to " + resolvedDefFile)
-		self.BuildVariant.AddOperation(raptor_data.Set("DEFFILEKEYWORD", deffile_keyword))
-		self.__debug("Set DEFFILEKEYWORD to '%s'",deffile_keyword)
-
-		# if this target type has a default TARGETPATH other than "" for
-		# resources then we need to add that default to all resources which
-		# do not explicitly set the TARGETPATH themselves.
-		tp = self.getDefaultResourceTargetPath(self.getTargetType())
-		if tp:
-			for i,var in enumerate(self.ResourceVariants):
-				# does this resource specify its own TARGETPATH?
-				needTP = True
-				for op in var.ops:
-					if isinstance(op, raptor_data.Set) \
-					and op.name == "TARGETPATH":
-						needTP = False
-						break
-				if needTP:
-					self.ResourceVariants[i].AddOperation(raptor_data.Set("TARGETPATH", tp))
-
-		# some core build configurations need to know about the resource builds, and
-		# some resource building configurations need knowledge of the core build
-		for resourceFile in self.__resourceFiles:
-			self.BuildVariant.AddOperation(raptor_data.Append("RESOURCEFILES", resourceFile))
-
-		for i,var in enumerate(self.ResourceVariants):
-			self.ResourceVariants[i].AddOperation(raptor_data.Set("MAIN_TARGET_lower", self.__TARGET.lower()))
-			self.ResourceVariants[i].AddOperation(raptor_data.Set("MAIN_REQUESTEDTARGETEXT", self.__TARGETEXT.lower()))
-
-		# Resolve combined capabilities as hex flags, for configurations that require them
-		capabilityFlag1 = 0
-		capabilityFlag2 = 0			# Always 0
-
-		for capability in self.__capabilities:
-			invert = 0
-
-			if capability.startswith('-'):
-				invert = 0xffffffff
-				capability = capability.lstrip('-')
-
-			if MMPRaptorBackend.supportedCapabilities.has_key(capability):
-				capabilityFlag1 = capabilityFlag1 ^ invert
-				capabilityFlag1 = capabilityFlag1 | MMPRaptorBackend.supportedCapabilities[capability]
-				capabilityFlag1 = capabilityFlag1 ^ invert
-
-		capabilityFlag1 = "%08xu" % capabilityFlag1
-		capabilityFlag2 = "%08xu" % capabilityFlag2
-
-		self.BuildVariant.AddOperation(raptor_data.Set("CAPABILITYFLAG1", capabilityFlag1))
-		self.__debug ("Set CAPABILITYFLAG1 to " + capabilityFlag1)
-		self.BuildVariant.AddOperation(raptor_data.Set("CAPABILITYFLAG2", capabilityFlag2))
-		self.__debug ("Set CAPABILITYFLAG2 to " + capabilityFlag2)
-
-		# For non-Feature Variant builds, the location of the product include hrh file is
-		# appended to the SYSTEMINCLUDE list
-		if not aBuildPlatform['ISFEATUREVARIANT']:
-			productIncludePath = str(aBuildPlatform['VARIANT_HRH'].Dir())
-			self.BuildVariant.AddOperation(raptor_data.Append("SYSTEMINCLUDE",productIncludePath))
-			self.__debug("Appending product include location %s to SYSTEMINCLUDE",productIncludePath)
-
-		# Specifying both a PAGED* and its opposite UNPAGED* keyword in a .mmp file
-		# will generate a warning and the last keyword specified will take effect.
-		self.__pageConflict.reverse()
-		if "PAGEDCODE" in self.__pageConflict and "UNPAGEDCODE" in self.__pageConflict:
-			for x in self.__pageConflict:
-				if x == "PAGEDCODE" or x == "UNPAGEDCODE":
-					self.__Raptor.Warn("Both PAGEDCODE and UNPAGEDCODE are specified. The last one %s will take effect" % x)
-					break
-		if "PAGEDDATA" in self.__pageConflict and "UNPAGEDDATA" in self.__pageConflict:
-			for x in self.__pageConflict:
-				if x == "PAGEDDATA" or x == "UNPAGEDDATA":
-					self.__Raptor.Warn("Both PAGEDDATA and UNPAGEDDATA are specified. The last one %s will take effect" % x)
-					break
-
-		# Set Debuggable
-		self.BuildVariant.AddOperation(raptor_data.Set("DEBUGGABLE", self.__debuggable))
-
-		if self.__explicitversion:
-			self.BuildVariant.AddOperation(raptor_data.Append("UNIQUETARGETPATH","$(TARGET_lower)_$(VERSIONHEX)_$(REQUESTEDTARGETEXT)",'/'))
-		else:
-			self.BuildVariant.AddOperation(raptor_data.Append("UNIQUETARGETPATH","$(TARGET_lower)_$(REQUESTEDTARGETEXT)",'/'))
-
-		# Put the list of sourcefiles in with one Set operation - saves memory
-		# and performance over using multiple Append operations.
-		self.BuildVariant.AddOperation(raptor_data.Set("SOURCE",
-						   " ".join(self.sources)))
-
-	def getTargetType(self):
-		"""Target type in lower case - the standard format"""
-		return self.__targettype.lower()
-
-	def resolveDefFile(self, aTARGET, aBuildPlatform):
-		"""Returns a fully resolved DEFFILE entry depending on .mmp file location and TARGET, DEFFILE and NOSTRICTDEF
-		entries in the .mmp file itself (where appropriate).
-		Is able to deal with target names that have multiple '.' characters e.g. messageintercept.esockdebug.dll
-		"""
-
-		resolvedDefFile = ""
-		platform = aBuildPlatform['PLATFORM']
-
-		# Not having a default .def file directory is a pretty strong indicator that
-		# .def files aren't supported for the particular platform
-		if PlatformDefaultDefFileDir.has_key(platform):
-			(targetname,targetext) = os.path.splitext(aTARGET)
-			(defname,defext) = os.path.splitext(self.deffile)
-			if defext=="":
-				defext = ".def"
-
-			# NOTE: WORKAROUND
-			if len(targetext) > 4:
-				targetname += defext
-
-			if not self.deffile:
-				resolvedDefFile = targetname
-			else:
-				if re.search('[\\|\/]$', self.deffile):
-					# If DEFFILE is *solely* a path, signified by ending in a slash, then TARGET is the
-					# basis for the default .def filename but with the specified path as prefix
-					resolvedDefFile = self.deffile + targetname
-
-				else:
-					resolvedDefFile = defname
-
-				resolvedDefFile = resolvedDefFile.replace('~', PlatformDefaultDefFileDir[platform])
-
-			if resolvedDefFile:
-				if not self.nostrictdef:
-					resolvedDefFile += 'u'
-
-				if self.__explicitversion:
-					resolvedDefFile += '{' + self.__versionhex + '}'
-
-				resolvedDefFile += defext
-
-
-				# If a DEFFILE statement doesn't specify a path in any shape or form, prepend the default .def file
-				# location based on the platform being built
-				if not re.search('[\\\/]+', self.deffile):
-					resolvedDefFile = '../'+PlatformDefaultDefFileDir[platform]+'/'+resolvedDefFile
-
-				resolvedDefFile = raptor_utilities.resolveSymbianPath(self.__defFileRoot, resolvedDefFile, 'DEFFILE', "", str(aBuildPlatform['EPOCROOT']))
-
-		return resolvedDefFile
-
-
-class MetaReader(object):
-	"""Entry point class for Symbian metadata processing.
-
-	Provides a means of integrating "traditional" Symbian metadata processing
-	with the new Raptor build system."""
-
-	filesplit_re = re.compile(r"^(?P<name>.*)\.(?P<ext>[^\.]*)$")
-
-	def __init__(self, aRaptor, configsToBuild):
-		self.__Raptor = aRaptor
-		self.BuildPlatforms = []
-		self.ExportPlatforms = []
-
-		# Get the version of CPP that we are using
-		metadata = self.__Raptor.cache.FindNamedVariant("meta")
-		evaluator = self.__Raptor.GetEvaluator(None, raptor_data.BuildUnit(metadata.name, [metadata]) )
-		self.__gnucpp = self.CheckValue(evaluator, "GNUCPP")
-		self.__defaultplatforms = self.CheckValue(evaluator, "DEFAULT_PLATFORMS")
-		self.__basedefaultplatforms = self.CheckValue(evaluator, "BASE_DEFAULT_PLATFORMS")
-		self.__baseuserdefaultplatforms = self.CheckValue(evaluator, "BASE_USER_DEFAULT_PLATFORMS")
-
-		# Only read each variant.cfg once
-		variantCfgs = {}
-
-		# Group the list of configurations into "build platforms".
-		# A build platform is a set of configurations which share
-		# the same metadata. In other words, a set of configurations
-		# for which the bld.inf and MMP files pre-process to exactly
-		# the same text.
-		platforms = {}
-
-		# Exports are not "platform dependent" but they are configuration
-		# dependent because different configs can have different EPOCROOT
-		# and VARIANT_HRH values. Each "build platform" has one associated
-		# "export platform" but several "build platforms" can be associated
-		# with the same "export platform".
-		exports = {}
-
-		for buildConfig in configsToBuild:
-			# get everything we need to know about the configuration
-			evaluator = self.__Raptor.GetEvaluator(None, buildConfig)
-
-			detail = {}
-			detail['PLATFORM'] = self.CheckValue(evaluator, "TRADITIONAL_PLATFORM")
-			epocroot = self.CheckValue(evaluator, "EPOCROOT")
-			detail['EPOCROOT'] = generic_path.Path(epocroot)
-
-			sbs_build_dir = self.CheckValue(evaluator, "SBS_BUILD_DIR")
-			detail['SBS_BUILD_DIR'] = generic_path.Path(sbs_build_dir)
-			flm_export_dir = self.CheckValue(evaluator, "FLM_EXPORT_DIR")
-			detail['FLM_EXPORT_DIR'] = generic_path.Path(flm_export_dir)
-			detail['CACHEID'] = flm_export_dir
-			if raptor_utilities.getOSPlatform().startswith("win"):
-				detail['PLATMACROS'] = self.CheckValue(evaluator,"PLATMACROS.WINDOWS")
-			else:
-				detail['PLATMACROS'] = self.CheckValue(evaluator,"PLATMACROS.LINUX")
-
-			# Apply OS variant provided we are not ignoring this
-			if not self.__Raptor.ignoreOsDetection:
-				self.__Raptor.Debug("Automatic OS detection enabled.")
-				self.ApplyOSVariant(buildConfig, epocroot)
-			else: # We are ignore OS versions so no detection required, so no variant will be applied
-				self.__Raptor.Debug("Automatic OS detection disabled.")
-
-			# is this a feature variant config or an ordinary variant
-			fv = evaluator.Get("FEATUREVARIANTNAME")
-			if fv:
-				variantHdr = self.CheckValue(evaluator, "VARIANT_HRH")
-				variantHRH = generic_path.Path(variantHdr)
-				detail['ISFEATUREVARIANT'] = True
-			else:
-				variantCfg = self.CheckValue(evaluator, "VARIANT_CFG")
-				variantCfg = generic_path.Path(variantCfg)
-				if not variantCfg in variantCfgs:
-					# get VARIANT_HRH from the variant.cfg file
-					varCfg = getVariantCfgDetail(detail['EPOCROOT'], variantCfg)
-					variantCfgs[variantCfg] = varCfg['VARIANT_HRH']
-					# we expect to always build ABIv2
-					if not 'ENABLE_ABIV2_MODE' in varCfg:
-						self.__Raptor.Warn("missing flag ENABLE_ABIV2_MODE in %s file. ABIV1 builds are not supported.",
-										   str(variantCfg))
-				variantHRH = variantCfgs[variantCfg]
-				detail['ISFEATUREVARIANT'] = False
-
-			detail['VARIANT_HRH'] = variantHRH
-			self.__Raptor.Info("'%s' uses variant hrh file '%s'", buildConfig.name, variantHRH)
-			detail['SYSTEMINCLUDE'] = self.CheckValue(evaluator, "SYSTEMINCLUDE")
-
-			detail['METADEPS'] = [] # Dependency targets for all metadata files in this platform
-
-			# find all the interface names we need
-			ifaceTypes = self.CheckValue(evaluator, "INTERFACE_TYPES")
-			interfaces = ifaceTypes.split()
-
-			for iface in interfaces:
-				detail[iface] = self.CheckValue(evaluator, "INTERFACE." + iface)
-
-			# not test code unless positively specified
-			detail['TESTCODE'] = self.CheckValue(evaluator, "TESTCODE", "")
-
-			# make a key that identifies this platform uniquely
-			# - used to tell us whether we have done the pre-processing
-			# we need already using another platform with compatible values.
-
-			key = str(detail['VARIANT_HRH']) \
-			 	+ str(detail['EPOCROOT']) \
-		    	+ detail['SYSTEMINCLUDE'] \
-		    	+ detail['PLATFORM']
-
-		    # Keep a short version of the key for use in filenames.
-			uniq = hashlib.md5()
-			uniq.update(key)
-
-			detail['key'] = key
-			detail['key_md5'] = "p_" + uniq.hexdigest()
-			del uniq
-
-			# compare this configuration to the ones we have already seen
-
-			# Is this an unseen export platform?
-			# concatenate all the values we care about in a fixed order
-			# and use that as a signature for the exports.
-			items = ['EPOCROOT', 'VARIANT_HRH', 'SYSTEMINCLUDE', 'TESTCODE', 'export']
-			export = ""
-			for i in  items:
-				if i in detail:
-					export += i + str(detail[i])
-
-			if export in exports:
-				# add this configuration to an existing export platform
-				index = exports[export]
-				self.ExportPlatforms[index]['configs'].append(buildConfig)
-			else:
-				# create a new export platform with this configuration
-				exports[export] = len(self.ExportPlatforms)
-				exp = copy.copy(detail)
-				exp['PLATFORM'] = 'EXPORT'
-				exp['configs']  = [buildConfig]
-				self.ExportPlatforms.append(exp)
-
-			# Is this an unseen build platform?
-			# concatenate all the values we care about in a fixed order
-			# and use that as a signature for the platform.
-			items = ['PLATFORM', 'EPOCROOT', 'VARIANT_HRH', 'SYSTEMINCLUDE', 'TESTCODE']
-			if raptor_utilities.getOSPlatform().startswith("win"):
-				items.append('PLATMACROS.WINDOWS')
-			else:
-				items.append('PLATMACROS.LINUX')
-
-			items.extend(interfaces)
-			platform = ""
-			for i in  items:
-				if i in detail:
-					platform += i + str(detail[i])
-
-			if platform in platforms:
-				# add this configuration to an existing build platform
-				index = platforms[platform]
-				self.BuildPlatforms[index]['configs'].append(buildConfig)
-			else:
-				# create a new build platform with this configuration
-				platforms[platform] = len(self.BuildPlatforms)
-				detail['configs'] = [buildConfig]
-				self.BuildPlatforms.append(detail)
-
-		# one platform is picked as the "default" for extracting things
-		# that are supposedly platform independent (e.g. PRJ_PLATFORMS)
-		self.defaultPlatform = self.ExportPlatforms[0]
-
-	def CheckValue(self, evaluator, key, default = None):
-		"""extract a value from an evaluator and raise an exception if None.
-
-		An optional default can be set to replace a None value."""
-		value = evaluator.Get(key)
-		if value == None:
-			if default == None:
-				raise MetaDataError("configuration " + evaluator.config.name +
-								    " has no variable " + key)
-			else:
-				return default
-		return value
-
-	def ReadBldInfFiles(self, aFileList, doExportOnly):
-		"""Take a list of bld.inf files and return a list of build specs.
-
-		The returned specification nodes will be suitable for all the build
-		configurations under consideration (using Filter nodes where required).
-		"""
-
-		# we need a Filter node per export platform
-		exportNodes = []
-		for i,ep in enumerate(self.ExportPlatforms):
-			filter = raptor_data.Filter("export_" + str(i))
-
-			# what configurations is this node active for?
-			for config in ep['configs']:
-				filter.AddConfigCondition(config.name)
-
-			exportNodes.append(filter)
-
-		# we need a Filter node per build platform
-		platformNodes = []
-		for i,bp in enumerate(self.BuildPlatforms):
-			filter = raptor_data.Filter("build_" + str(i))
-
-			# what configurations is this node active for?
-			for config in bp['configs']:
-				filter.AddConfigCondition(config.name)
-
-			# platform-wide data
-			platformVar = raptor_data.Variant()
-			platformVar.AddOperation(raptor_data.Set("PRODUCT_INCLUDE",
-													 str(bp['VARIANT_HRH'])))
-
-			filter.AddVariant(platformVar)
-			platformNodes.append(filter)
-
-		# check that each bld.inf exists and add a Specification node for it
-		# to the nodes of the export and build platforms that it supports.
-		for bif in aFileList:
-			if bif.isFile():
-				self.__Raptor.Info("Processing %s", str(bif))
-				try:
-					self.AddComponentNodes(bif, exportNodes, platformNodes)
-
-				except MetaDataError, e:
-					self.__Raptor.Error(e.Text, bldinf=str(bif))
-					if not self.__Raptor.keepGoing:
-						return []
-			else:
-				self.__Raptor.Error("build info file does not exist", bldinf=str(bif))
-				if not self.__Raptor.keepGoing:
-					return []
-
-		# now we have the top-level structure in place...
-		#
-		# <filter exports 1>
-		#		<spec bld.inf 1 />
-		#		<spec bld.inf 2 />
-		#		<spec bld.inf N /> </filter>
-		# <filter build 1>
-		#		<spec bld.inf 1 />
-		#		<spec bld.inf 2 />
-		#		<spec bld.inf N /> </filter>
-		# <filter build 2>
-		#		<spec bld.inf 1 />
-		#		<spec bld.inf 2 />
-		#		<spec bld.inf N /> </filter>
-		# <filter build 3>
-		#		<spec bld.inf 1 />
-		#		<spec bld.inf 2 />
-		#		<spec bld.inf N /> </filter>
-		#
-		# assuming that every bld.inf builds for every platform and all
-		# exports go to the same place. clearly, it is more likely that
-		# some filters have less than N child nodes. in bigger builds there
-		# will also be more than one export platform.
-
-		# we now need to process the EXPORTS for all the bld.inf nodes
-		# before we can do anything else (because raptor itself must do
-		# some exports before the MMP files that include them can be
-		# processed).
-		for i,p in enumerate(exportNodes):
-			exportPlatform = self.ExportPlatforms[i]
-			for s in p.GetChildSpecs():
-				try:
-					self.ProcessExports(s, exportPlatform)
-
-				except MetaDataError, e:
-					self.__Raptor.Error("%s",e.Text)
-					if not self.__Raptor.keepGoing:
-						return []
-
-		# this is a switch to return the function at this point if export
-		# only option is specified in the run
-		if (self.__Raptor.doExportOnly):
-			self.__Raptor.Info("Processing Exports only")
-			return[]
-
-		# after exports are done we can look to see if there are any
-		# new Interfaces which can be used for EXTENSIONS. Make sure
-		# that we only load each cache once as some export platforms
-		# may share a directory.
-		doneID = {}
-		for ep in self.ExportPlatforms:
-			flmDir = ep["FLM_EXPORT_DIR"]
-			cid = ep["CACHEID"]
-			if flmDir.isDir() and not cid in doneID:
-				self.__Raptor.cache.Load(flmDir, cid)
-			doneID[cid] = True
-
-		# finally we can process all the other parts of the bld.inf nodes.
-		# Keep a list of the projects we were asked to build so that we can
-		# tell at the end if there were any we didn't know about.
-		self.projectList = list(self.__Raptor.projects)
-		for i,p in enumerate(platformNodes):
-			buildPlatform = self.BuildPlatforms[i]
-			for s in p.GetChildSpecs():
-				try:
-					self.ProcessTEMs(s, buildPlatform)
-					self.ProcessMMPs(s, buildPlatform)
-
-				except MetaDataError, e:
-					self.__Raptor.Error(e.Text)
-					if not self.__Raptor.keepGoing:
-						return []
-
-		for badProj in self.projectList:
-			self.__Raptor.Warn("Can't find project '%s' in any build info file", badProj)
-
-		# everything is specified
-		return exportNodes + platformNodes
-
-	def ModuleName(self,aBldInfPath):
-		"""Calculate the name of the ROM/emulator batch files that run the tests"""
-
-		def LeftPortionOf(pth,sep):
-			""" Internal function to return portion of str that is to the left of sep. 
-			The partition is case-insentive."""
-			length = len((pth.lower().partition(sep.lower()))[0])
-			return pth[0:length]
-			
-		modulePath = LeftPortionOf(LeftPortionOf(os.path.dirname(aBldInfPath), "group"), "ongoing")
-		moduleName = os.path.basename(modulePath.strip("/"))
-		
-		# Ensure that ModuleName does not return blank, if the above calculation determines
-		# that moduleName is blank
-		if moduleName == "" or moduleName.endswith(":"):
-			moduleName = "module"
-		return moduleName
-
-
-	def AddComponentNodes(self, buildFile, exportNodes, platformNodes):
-		"""Add Specification nodes for a bld.inf to the appropriate platforms."""
-		bldInfFile = BldInfFile(buildFile, self.__gnucpp, self.__Raptor)
-
-		specName = self.getSpecName(buildFile, fullPath=True)
-
-		if isinstance(buildFile, raptor_xml.SystemModelComponent):
-			# this component came from a system_definition.xml
-			layer = buildFile.GetContainerName("layer")
-			component = buildFile.GetContainerName("component")
-		else:
-			# this is a plain old bld.inf file from the command-line
-			layer = ""
-			component = ""
-
-		# exports are independent of build platform
-		for i,ep in enumerate(self.ExportPlatforms):
-			specNode = raptor_data.Specification(specName)
-
-			# keep the BldInfFile object for later
-			specNode.bldinf = bldInfFile
-
-			# add some basic data in a component-wide variant
-			var = raptor_data.Variant()
-			var.AddOperation(raptor_data.Set("COMPONENT_META", str(buildFile)))
-			var.AddOperation(raptor_data.Set("COMPONENT_NAME", component))
-			var.AddOperation(raptor_data.Set("COMPONENT_LAYER", layer))
-			specNode.AddVariant(var)
-
-			# add this bld.inf Specification to the export platform
-			exportNodes[i].AddChild(specNode)
-
-		# get the relevant build platforms
-		listedPlatforms = bldInfFile.getBuildPlatforms(self.defaultPlatform)
-		platforms = getBuildableBldInfBuildPlatforms(listedPlatforms,
-													self.__defaultplatforms,
-													self.__basedefaultplatforms,
-													self.__baseuserdefaultplatforms)
-
-
-
-		outputDir = BldInfFile.outputPathFragment(buildFile)
-
-		# Calculate "module name"
-		modulename = self.ModuleName(str(buildFile))
-
-		for i,bp in enumerate(self.BuildPlatforms):
-			if bp['PLATFORM'] in platforms:
-				specNode = raptor_data.Specification(specName)
-
-				# keep the BldInfFile object for later
-				specNode.bldinf = bldInfFile
-
-				# add some basic data in a component-wide variant
-				var = raptor_data.Variant()
-				var.AddOperation(raptor_data.Set("COMPONENT_META",str(buildFile)))
-				var.AddOperation(raptor_data.Set("COMPONENT_NAME", component))
-				var.AddOperation(raptor_data.Set("COMPONENT_LAYER", layer))
-				var.AddOperation(raptor_data.Set("MODULE", modulename))
-				var.AddOperation(raptor_data.Append("OUTPUTPATHOFFSET", outputDir, '/'))
-				var.AddOperation(raptor_data.Append("OUTPUTPATH", outputDir, '/'))
-				var.AddOperation(raptor_data.Append("BLDINF_OUTPUTPATH",outputDir, '/'))
-
-				var.AddOperation(raptor_data.Set("TEST_OPTION", specNode.bldinf.getRomTestType(bp)))
-				specNode.AddVariant(var)
-
-				# add this bld.inf Specification to the build platform
-				platformNodes[i].AddChild(specNode)
-
-	def ProcessExports(self, componentNode, exportPlatform):
-		"""Do the exports for a given platform and skeleton bld.inf node.
-
-		This will actually perform exports as certain types of files (.mmh)
-		are required to be in place before the rest of the bld.inf node
-		(and parts of other bld.inf nodes) can be processed.
-
-		[some MMP files #include exported .mmh files]
-		"""
-		if exportPlatform["TESTCODE"]:
-			exports = componentNode.bldinf.getTestExports(exportPlatform)
-		else:
-			exports = componentNode.bldinf.getExports(exportPlatform)
-
-		self.__Raptor.Debug("%i exports for %s",
-							len(exports), str(componentNode.bldinf.filename))
-		if exports:
-
-			# each export is either a 'copy' or 'unzip'
-			# maybe we should trap multiple exports to the same location here?
-			epocroot = str(exportPlatform["EPOCROOT"])
-			bldinf_filename = str(componentNode.bldinf.filename)
-			exportwhatlog="<whatlog bldinf='%s' mmp='' config=''>\n" % bldinf_filename
-			for export in exports:
-				expSrc = export.getSource()
-				expDstList = export.getDestination() # Might not be a list in all circumstances
-
-				# make it a list if it isn't
-				if not isinstance(expDstList, list):
-					expDstList = [expDstList]
-
-				fromFile = generic_path.Path(expSrc.replace("$(EPOCROOT)", epocroot))
-
-				# For each destination in the destination list, add an export target, perform it if required.
-				# This ensures that make knows the dependency situation but that the export is made
-				# before any other part of the metadata requires it.  It also helps with the build
-				# from clean situation where we can't use order only prerequisites.
-				for expDst in expDstList:
-					toFile = generic_path.Path(expDst.replace("$(EPOCROOT)", epocroot))
-					try:
-						if export.getAction() == "copy":
-							# export the file
-							exportwhatlog += self.CopyExport(fromFile, toFile, bldinf_filename)
-						else:
-							# unzip the zip
-							exportwhatlog += ("<archive zipfile='" + str(fromFile) + "'>\n")
-							members = self.UnzipExport(fromFile, toFile,
-									str(exportPlatform['SBS_BUILD_DIR']),
-									bldinf_filename)
-							if members != None:
-								exportwhatlog += members
-							exportwhatlog += "</archive>\n"
-					except MetaDataError, e:
-						if self.__Raptor.keepGoing:
-							self.__Raptor.Error("%s",e.Text, bldinf=bldinf_filename)
-						else:
-							raise e
-			exportwhatlog+="</whatlog>\n"
-			self.__Raptor.PrintXML("%s",exportwhatlog)
-
-	def CopyExport(self, _source, _destination, bldInfFile):
-		"""Copy the source file to the destination file (create a directory
-		   to copy into if it does not exist). Don't copy if the destination
-		   file exists and has an equal or newer modification time."""
-		source = generic_path.Path(str(_source).replace('%20',' '))
-		destination = generic_path.Path(str(_destination).replace('%20',' '))
-		dest_str = str(destination)
-		source_str = str(source)
-
-		exportwhatlog="<export destination='" + dest_str + "' source='" + \
-				source_str + "'/>\n"
-
-		try:
-
-
-			destDir = destination.Dir()
-			if not destDir.isDir():
-				os.makedirs(str(destDir))
-				shutil.copyfile(source_str, dest_str)
-				return exportwhatlog
-
-			sourceMTime = 0
-			destMTime = 0
-			try:
-				sourceMTime = os.stat(source_str)[stat.ST_MTIME]
-				destMTime = os.stat(dest_str)[stat.ST_MTIME]
-			except OSError, e:
-				if sourceMTime == 0:
-					message = "Source of export does not exist:  " + str(source)
-					if not self.__Raptor.keepGoing:
-						raise MetaDataError(message)
-					else:
-						self.__Raptor.Error(message, bldinf=bldInfFile)
-
-			if destMTime == 0 or destMTime < sourceMTime:
-				if os.path.exists(dest_str):
-					os.chmod(dest_str,stat.S_IREAD | stat.S_IWRITE)
-				shutil.copyfile(source_str, dest_str)
-				self.__Raptor.Info("Copied %s to %s", source_str, dest_str)
-			else:
-				self.__Raptor.Info("Up-to-date: %s", dest_str)
-
-
-		except Exception,e:
-			message = "Could not export " + source_str + " to " + dest_str + " : " + str(e)
-			if not self.__Raptor.keepGoing:
-				raise MetaDataError(message)
-			else:
-				self.__Raptor.Error(message, bldinf=bldInfFile)
-
-		return exportwhatlog
-
-
-	def UnzipExport(self, _source, _destination, _sbs_build_dir, bldinf_filename):
-		"""Unzip the source zipfile into the destination directory
-		   but only if the markerfile does not already exist there
-		   or it does exist but is older than the zipfile.
-		   the markerfile is comprised of the name of the zipfile
-		   with the ".zip" removed and ".unzipped" added.
-		"""
-
-		# Insert spaces into file if they are there
-		source = str(_source).replace('%20',' ')
-		destination = str(_destination).replace('%20',' ')
-		sanitisedSource = raptor_utilities.sanitise(source)
-		sanitisedDestination = raptor_utilities.sanitise(destination)
-
-		destination = str(_destination).replace('%20',' ')
-		exportwhatlog = ""
-
-
-		try:
-			if not _destination.isDir():
-				os.makedirs(destination)
-
-			# Form the directory to contain the unzipped marker files, and make the directory if require.
-			markerfiledir = generic_path.Path(_sbs_build_dir)
-			if not markerfiledir.isDir():
-				os.makedirs(str(markerfiledir))
-
-			# Form the marker file name and convert to Python string
-			markerfilename = str(generic_path.Join(markerfiledir, sanitisedSource + sanitisedDestination + ".unzipped"))
-
-			# Don't unzip if the marker file is already there or more uptodate
-			sourceMTime = 0
-			destMTime = 0
-			try:
-				sourceMTime = os.stat(source)[stat.ST_MTIME]
-				destMTime = os.stat(markerfilename)[stat.ST_MTIME]
-			except OSError, e:
-				if sourceMTime == 0:
-					raise MetaDataError("Source zip for export does not exist:  " + source)
-			if destMTime != 0 and destMTime >= sourceMTime:
-				# This file has already been unzipped. Print members then return
-				exportzip = zipfile.ZipFile(source, 'r')
-				files = exportzip.namelist()
-				files.sort()
-
-				for file in files:
-					if not file.endswith('/'):
-						expfilename = str(generic_path.Join(destination, file))
-						exportwhatlog += "<member>" + expfilename + "</member>\n"
-
-				self.__Raptor.PrintXML("<clean bldinf='" + bldinf_filename + "' mmp='' config=''>\n")
-				self.__Raptor.PrintXML("<zipmarker>" + markerfilename + "</zipmarker>\n")
-				self.__Raptor.PrintXML("</clean>\n")
-
-				return exportwhatlog
-
-			exportzip = zipfile.ZipFile(source, 'r')
-			files = exportzip.namelist()
-			files.sort()
-			filecount = 0
-			for file in files:
-				expfilename = str(generic_path.Join(destination, file))
-				if file.endswith('/'):
-					try:
-						os.makedirs(expfilename)
-					except OSError, e:
-						pass # errors to do with "already exists" are not interesting.
-				else:
-					try:
-						os.makedirs(os.path.split(expfilename)[0])
-					except OSError, e:
-						pass # errors to do with "already exists" are not interesting.
-
-					try:
-						if os.path.exists(expfilename):
-							os.chmod(expfilename,stat.S_IREAD | stat.S_IWRITE)
-						expfile = open(expfilename, 'wb')
-						expfile.write(exportzip.read(file))
-						expfile.close()
-						# Each file keeps its modified time the same as what it was before unzipping
-						accesstime = time.time()
-						datetime = exportzip.getinfo(file).date_time
-						timeTuple=(int(datetime[0]), int(datetime[1]), int(datetime[2]), int(datetime[3]), \
-									int(datetime[4]), int(datetime[5]), int(0), int(0), int(0))
-						modifiedtime = time.mktime(timeTuple)
-						os.utime(expfilename,(accesstime, modifiedtime))
-
-						filecount += 1
-						exportwhatlog+="<member>" + expfilename + "</member>\n"
-					except IOError, e:
-						message = "Could not unzip %s to %s: file %s: %s" %(source, destination, expfilename, str(e))
-						if not self.__Raptor.keepGoing:
-							raise MetaDataError(message)
-						else:
-							self.__Raptor.Error(message, bldinf=bldinf_filename)
-
-			markerfile = open(markerfilename, 'wb+')
-			markerfile.close()
-			self.__Raptor.PrintXML("<clean bldinf='" + bldinf_filename + "' mmp='' config=''>\n")
-			self.__Raptor.PrintXML("<zipmarker>" + markerfilename +	"</zipmarker>\n")
-			self.__Raptor.PrintXML("</clean>\n")
-
-		except IOError:
-			self.__Raptor.Warn("Problem while unzipping export %s to %s: %s",source,destination,str(e))
-
-		self.__Raptor.Info("Unzipped %d files from %s to %s", filecount, source, destination)
-		return exportwhatlog
-
-	def ProcessTEMs(self, componentNode, buildPlatform):
-		"""Add Template Extension Makefile nodes for a given platform
-		   to a skeleton bld.inf node.
-
-		This happens after exports have been handled.
-		"""
-		if buildPlatform["ISFEATUREVARIANT"]:
-			return	# feature variation does not run extensions at all
-		
-		if buildPlatform["TESTCODE"]:
-			extensions = componentNode.bldinf.getTestExtensions(buildPlatform)
-		else:
-			extensions = componentNode.bldinf.getExtensions(buildPlatform)
-
-		self.__Raptor.Debug("%i template extension makefiles for %s",
-							len(extensions), str(componentNode.bldinf.filename))
-
-		for i,extension in enumerate(extensions):
-			if self.__Raptor.projects:
-				if not extension.nametag in self.__Raptor.projects:
-					self.__Raptor.Debug("Skipping %s", extension.getMakefile())
-					continue
-				elif extension.nametag in self.projectList:
-					self.projectList.remove(extension.nametag)
-
-			extensionSpec = raptor_data.Specification("extension" + str(i))
-
-			interface = buildPlatform["extension"]
-			customInterface = False
-
-			# is there an FLM replacement for this extension?
-			if extension.interface:
-				try:
-					interface = self.__Raptor.cache.FindNamedInterface(extension.interface, buildPlatform["CACHEID"])
-					customInterface = True
-				except KeyError:
-					# no, there isn't an FLM
-					pass
-
-			extensionSpec.SetInterface(interface)
-
-			var = raptor_data.Variant()
-			var.AddOperation(raptor_data.Set("EPOCBLD", "$(OUTPUTPATH)"))
-			var.AddOperation(raptor_data.Set("PLATFORM", buildPlatform["PLATFORM"]))
-			var.AddOperation(raptor_data.Set("PLATFORM_PATH", buildPlatform["PLATFORM"].lower()))
-			var.AddOperation(raptor_data.Set("CFG", "$(VARIANTTYPE)"))
-			var.AddOperation(raptor_data.Set("CFG_PATH", "$(VARIANTTYPE)"))
-			var.AddOperation(raptor_data.Set("GENERATEDCPP", "$(OUTPUTPATH)"))
-			var.AddOperation(raptor_data.Set("TEMPLATE_EXTENSION_MAKEFILE", extension.getMakefile()))
-			var.AddOperation(raptor_data.Set("TEMCOUNT", str(i)))
-
-			# Extension inputs are added to the build spec.
-			# '$'s are escaped so that they are not expanded by Raptor or
-			# by Make in the call to the FLM
-			# The Extension makefiles are supposed to expand them themselves
-			# Path separators need not be parameterised anymore
-			# as bash is the standard shell
-			standardVariables = extension.getStandardVariables()
-			for standardVariable in standardVariables.keys():
-				self.__Raptor.Debug("Set %s=%s", standardVariable, standardVariables[standardVariable])
-				value = standardVariables[standardVariable].replace('$(', '$$$$(')
-				value = value.replace('$/', '/').replace('$;', ':')
-				var.AddOperation(raptor_data.Set(standardVariable, value))
-
-			# . . . as with the standard variables but the names and number
-			# of options are not known in advance so we add them to
-			# a "structure" that is self-describing
-			var.AddOperation(raptor_data.Set("O._MEMBERS", ""))
-			options = extension.getOptions()
-			for option in options:
-				self.__Raptor.Debug("Set %s=%s", option, options[option])
-				value = options[option].replace('$(EPOCROOT)', '$(EPOCROOT)/')
-				value = value.replace('$(', '$$$$(')
-				value = value.replace('$/', '/').replace('$;', ':')
-				value = value.replace('$/', '/').replace('$;', ':')
-
-				if customInterface:
-					var.AddOperation(raptor_data.Set(option, value))
-				else:
-					var.AddOperation(raptor_data.Append("O._MEMBERS", option))
-					var.AddOperation(raptor_data.Set("O." + option, value))
-
-			extensionSpec.AddVariant(var)
-			componentNode.AddChild(extensionSpec)
-
-
-	def ProcessMMPs(self, componentNode, buildPlatform):
-		"""Add project nodes for a given platform to a skeleton bld.inf node.
-
-		This happens after exports have been handled.
-		"""
-		gnuList = []
-		makefileList = []
-
-		if buildPlatform["TESTCODE"]:
-			MMPList = componentNode.bldinf.getTestMMPList(buildPlatform)
-		else:
-			MMPList = componentNode.bldinf.getMMPList(buildPlatform)
-
-		bldInfFile = componentNode.bldinf.filename
-
-		for mmpFileEntry in MMPList['mmpFileList']:
-			projectname = mmpFileEntry.filename.File().lower()
-
-			if self.__Raptor.projects:
-				if not projectname in self.__Raptor.projects:
-					self.__Raptor.Debug("Skipping %s", str(mmpFileEntry.filename))
-					continue
-				elif projectname in self.projectList:
-					self.projectList.remove(projectname)
-
-			foundmmpfile = (mmpFileEntry.filename).FindCaseless()
-
-			if foundmmpfile == None:
-				self.__Raptor.Error("Can't find mmp file '%s'", str(mmpFileEntry.filename), bldinf=str(bldInfFile))
-				continue
-
-			mmpFile = MMPFile(foundmmpfile,
-								   self.__gnucpp,
-								   bldinf = componentNode.bldinf,
-								   log = self.__Raptor)
-
-			mmpFilename = mmpFile.filename
-
-			self.__Raptor.Info("Processing %s for platform %s",
-							   str(mmpFilename),
-							   " + ".join([x.name for x in buildPlatform["configs"]]))
-
-			# Run the Parser
-			# The backend supplies the actions
-			content = mmpFile.getContent(buildPlatform)
-			backend = MMPRaptorBackend(self.__Raptor, str(mmpFilename), str(bldInfFile))
-			parser  = MMPParser(backend)
-			parseresult = None
-			try:
-				parseresult = parser.mmp.parseString(content)
-			except ParseException,e:
-				self.__Raptor.Debug(e) # basically ignore parse exceptions
-
-			if (not parseresult) or (parseresult[0] != 'MMP'):
-				self.__Raptor.Error("The MMP Parser didn't recognise the mmp file '%s'",
-					                str(mmpFileEntry.filename), 
-					                bldinf=str(bldInfFile))
-				self.__Raptor.Debug(content)
-				self.__Raptor.Debug("The parse result was %s", parseresult)
-			else:
-				backend.finalise(buildPlatform)
-
-			# feature variation only processes FEATUREVARIANT binaries
-			if buildPlatform["ISFEATUREVARIANT"] and not backend.featureVariant:
-				continue
-			
-			# now build the specification tree
-			mmpSpec = raptor_data.Specification(self.getSpecName(mmpFilename))
-			var = backend.BuildVariant
-
-			var.AddOperation(raptor_data.Set("PROJECT_META", str(mmpFilename)))
-
-			# If it is a TESTMMPFILE section, the FLM needs to know about it
-			if buildPlatform["TESTCODE"] and (mmpFileEntry.testoption in
-					["manual", "auto"]):
-
-				var.AddOperation(raptor_data.Set("TESTPATH",
-						mmpFileEntry.testoption.lower() + ".bat"))
-
-			# The output path for objects, stringtables and bitmaps specified by
-			# this MMP.  Adding in the requested target extension prevents build
-			# "fouling" in cases where there are several mmp targets which only differ
-			# by the requested extension. e.g. elocl.01 and elocl.18
-			var.AddOperation(raptor_data.Append("OUTPUTPATH","$(UNIQUETARGETPATH)",'/'))
-
-			# If the bld.inf entry for this MMP had the BUILD_AS_ARM option then
-			# tell the FLM.
-			if mmpFileEntry.armoption:
-				var.AddOperation(raptor_data.Set("ALWAYS_BUILD_AS_ARM","1"))
-
-			# what interface builds this node?
-			try:
-				interfaceName = buildPlatform[backend.getTargetType()]
-				mmpSpec.SetInterface(interfaceName)
-			except KeyError:
-				self.__Raptor.Error("Unsupported target type '%s' in %s",
-								    backend.getTargetType(),
-								    str(mmpFileEntry.filename),
-								    bldinf=str(bldInfFile))
-				continue
-
-			# Although not part of the MMP, some MMP-based build specs additionally require knowledge of their
-			# container bld.inf exported headers
-			for export in componentNode.bldinf.getExports(buildPlatform):
-				destination = export.getDestination()
-				if isinstance(destination, list):
-					exportfile = str(destination[0])
-				else:
-					exportfile = str(destination)
-
-				if re.search('\.h',exportfile,re.IGNORECASE):
-					var.AddOperation(raptor_data.Append("EXPORTHEADERS", str(exportfile)))
-
-			# now we have something worth adding to the component
-			mmpSpec.AddVariant(var)
-			componentNode.AddChild(mmpSpec)
-
-			# resources, stringtables and bitmaps are sub-nodes of this project
-			# (do not add these for feature variant builds)
-			
-			if not buildPlatform["ISFEATUREVARIANT"]:
-				# Buildspec for Resource files
-				for i,rvar in enumerate(backend.ResourceVariants):
-					resourceSpec = raptor_data.Specification('resource' + str(i))
-					resourceSpec.SetInterface(buildPlatform['resource'])
-					resourceSpec.AddVariant(rvar)
-					mmpSpec.AddChild(resourceSpec)
-
-				# Buildspec for String Tables
-				for i,stvar in enumerate(backend.StringTableVariants):
-					stringTableSpec = raptor_data.Specification('stringtable' + str(i))
-					stringTableSpec.SetInterface(buildPlatform['stringtable'])
-					stringTableSpec.AddVariant(stvar)
-					mmpSpec.AddChild(stringTableSpec)
-
-				# Buildspec for Bitmaps
-				for i,bvar in enumerate(backend.BitmapVariants):
-					bitmapSpec = raptor_data.Specification('bitmap' + str(i))
-					bitmapSpec.SetInterface(buildPlatform['bitmap'])
-					bitmapSpec.AddVariant(bvar)
-					mmpSpec.AddChild(bitmapSpec)
-
-		# feature variation does not run extensions at all
-		# so return without considering .*MAKEFILE sections
-		if buildPlatform["ISFEATUREVARIANT"]:
-			return
-			
-		# Build spec for gnumakefile
-		for g in MMPList['gnuList']:
-			projectname = g.getMakefileName().lower()
-
-			if self.__Raptor.projects:
-				if not projectname in self.__Raptor.projects:
-					self.__Raptor.Debug("Skipping %s", str(g.getMakefileName()))
-					continue
-				elif projectname in self.projectList:
-					self.projectList.remove(projectname)
-
-			self.__Raptor.Debug("%i gnumakefile extension makefiles for %s",
-						len(gnuList), str(componentNode.bldinf.filename))
-			var = raptor_data.Variant()
-			gnuSpec = raptor_data.Specification("gnumakefile " + str(g.getMakefileName()))
-			interface = buildPlatform["ext_makefile"]
-			gnuSpec.SetInterface(interface)
-			gnumakefilePath = raptor_utilities.resolveSymbianPath(str(bldInfFile), g.getMakefileName())
-			var.AddOperation(raptor_data.Set("EPOCBLD", "$(OUTPUTPATH)"))
-			var.AddOperation(raptor_data.Set("PLATFORM", buildPlatform["PLATFORM"]))
-			var.AddOperation(raptor_data.Set("EXTMAKEFILENAME", g.getMakefileName()))
-			var.AddOperation(raptor_data.Set("DIRECTORY",g.getMakeDirectory()))
-			var.AddOperation(raptor_data.Set("CFG","$(VARIANTTYPE)"))
-			standardVariables = g.getStandardVariables()
-			for standardVariable in standardVariables.keys():
-				self.__Raptor.Debug("Set %s=%s", standardVariable, standardVariables[standardVariable])
-				value = standardVariables[standardVariable].replace('$(', '$$$$(')
-				value = value.replace('$/', '/').replace('$;', ':')
-				var.AddOperation(raptor_data.Set(standardVariable, value))
-			gnuSpec.AddVariant(var)
-			componentNode.AddChild(gnuSpec)
-
-		# Build spec for makefile
-		for m in MMPList['makefileList']:
-			projectname = m.getMakefileName().lower()
-
-			if self.__Raptor.projects:
-				if not projectname in self.__Raptor.projects:
-					self.__Raptor.Debug("Skipping %s", str(m.getMakefileName()))
-					continue
-				elif projectname in self.projectList:
-					projectList.remove(projectname)
-
-			self.__Raptor.Debug("%i makefile extension makefiles for %s",
-						len(makefileList), str(componentNode.bldinf.filename))
-			var = raptor_data.Variant()
-			gnuSpec = raptor_data.Specification("makefile " + str(m.getMakefileName()))
-			interface = buildPlatform["ext_makefile"]
-			gnuSpec.SetInterface(interface)
-			gnumakefilePath = raptor_utilities.resolveSymbianPath(str(bldInfFile), m.getMakefileName())
-			var.AddOperation(raptor_data.Set("EPOCBLD", "$(OUTPUTPATH)"))
-			var.AddOperation(raptor_data.Set("PLATFORM", buildPlatform["PLATFORM"]))
-			var.AddOperation(raptor_data.Set("EXTMAKEFILENAME", m.getMakefileName()))
-			var.AddOperation(raptor_data.Set("DIRECTORY",m.getMakeDirectory()))
-			var.AddOperation(raptor_data.Set("CFG","$(VARIANTTYPE)"))
-			var.AddOperation(raptor_data.Set("USENMAKE","1"))
-			standardVariables = m.getStandardVariables()
-			for standardVariable in standardVariables.keys():
-				self.__Raptor.Debug("Set %s=%s", standardVariable, standardVariables[standardVariable])
-				value = standardVariables[standardVariable].replace('$(', '$$$$(')
-				value = value.replace('$/', '/').replace('$;', ':')
-				var.AddOperation(raptor_data.Set(standardVariable, value))
-			gnuSpec.AddVariant(var)
-			componentNode.AddChild(gnuSpec)
-
-	def getSpecName(self, aFileRoot, fullPath=False):
-		"""Returns a build spec name: this is the file root (full path
-		or simple file name) made safe for use as a file name."""
-
-		if fullPath:
-			specName = str(aFileRoot).replace("/","_")
-			specName = specName.replace(":","")
-		else:
-			specName = aFileRoot.File()
-
-		return specName.lower()
-
-	def ApplyOSVariant(self, aBuildUnit, aEpocroot):
-		# Form path to kif.xml and path to buildinfo.txt
-		kifXmlPath = generic_path.Join(aEpocroot, "epoc32", "data","kif.xml")
-		buildInfoTxtPath = generic_path.Join(aEpocroot, "epoc32", "data","buildinfo.txt")
-
-		# Start with osVersion being None. This variable is a string and does two things:
-		# 1) is a representation of the OS version
-		# 2) is potentially the name of a variant
-		osVersion = None
-		if kifXmlPath.isFile(): # kif.xml exists so try to read it
-			osVersion = getOsVerFromKifXml(str(kifXmlPath))
-			if osVersion != None:
-				self.__Raptor.Info("OS version \"%s\" determined from file \"%s\"" % (osVersion, kifXmlPath))
-
-		# OS version was not determined from the kif.xml, e.g. because it doesn't exist
-		# or there was a problem parsing it. So, we fall over to using the buildinfo.txt
-		if osVersion == None and buildInfoTxtPath.isFile():
-			osVersion = getOsVerFromBuildInfoTxt(str(buildInfoTxtPath))
-			if osVersion != None:
-				self.__Raptor.Info("OS version \"%s\" determined from file \"%s\"" % (osVersion, buildInfoTxtPath))
-
-		# If we determined a non-empty string for the OS Version, attempt to apply it
-		if osVersion and osVersion in self.__Raptor.cache.variants:
-			self.__Raptor.Info("applying the OS variant to the configuration \"%s\"." % aBuildUnit.name)
-			aBuildUnit.variants.append(self.__Raptor.cache.variants[osVersion])
-		else:
-			self.__Raptor.Info("no OS variant for the configuration \"%s\"." % aBuildUnit.name)
-
+#
+# 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: 
+# This module includes classes that process bld.inf and .mmp files to
+# generate Raptor build specifications
+#
+
+import copy
+import re
+import os.path
+import shutil
+import stat
+import hashlib
+import base64
+
+import raptor
+import raptor_data
+import raptor_utilities
+import raptor_xml
+import generic_path
+import subprocess
+import zipfile
+from xml.sax.saxutils import escape
+from mmpparser import *
+
+import time
+
+
+PiggyBackedBuildPlatforms = {'ARMV5':['GCCXML']}
+
+PlatformDefaultDefFileDir = {'WINSCW':'bwins',
+				  'ARMV5' :'eabi',
+				  'ARMV5SMP' :'eabi',
+				  'GCCXML':'eabi',
+				  'ARMV6':'eabi',
+				  'ARMV7' : 'eabi',
+				  'ARMV7SMP' : 'eabi'}
+
+def getVariantCfgDetail(aEPOCROOT, aVariantCfgFile):
+	"""Obtain pertinent build related detail from the Symbian variant.cfg file.
+
+	This variant.cfg file, usually located relative to $(EPOCROOT), contains:
+	(1) The $(EPOCROOT) relative location of the primary .hrh file used to configure the specific OS variant build
+	(2) A flag determining whether ARMV5 represents an ABIV1 or ABIV2 build (currently unused by Raptor)."""
+
+	variantCfgDetails = {}
+	variantCfgFile = None
+
+	try:
+		variantCfgFile = open(str(aVariantCfgFile))
+	except IOError, (number, message):
+		raise MetaDataError("Could not read variant configuration file "+str(aVariantCfgFile)+" ("+message+")")
+
+	for line in variantCfgFile.readlines():
+		if re.search('^(\s$|\s*#)', line):
+			continue
+		# Note that this detection of the .hrh file matches the command line build i.e. ".hrh" somewhere
+		# in the specified line
+		elif re.search('\.hrh', line, re.I):
+			variantHrh = line.strip()
+			if variantHrh.startswith('\\') or variantHrh.startswith('/'):
+				variantHrh = variantHrh[1:]
+			variantHrh = aEPOCROOT.Append(variantHrh)
+			variantCfgDetails['VARIANT_HRH'] = variantHrh
+		else:
+			lineContent = line.split()
+
+			if len(lineContent) == 1:
+				variantCfgDetails[lineContent.pop(0)] = 1
+			else:
+				variantCfgDetails[lineContent.pop(0)] = lineContent
+
+	variantCfgFile.close()
+
+	if not variantCfgDetails.has_key('VARIANT_HRH'):
+		raise MetaDataError("No variant file specified in "+str(aVariantCfgFile))
+	if not variantHrh.isFile():
+		raise MetaDataError("Variant file "+str(variantHrh)+" does not exist")
+
+	return variantCfgDetails
+
+def getOsVerFromKifXml(aPathToKifXml):
+	"""Obtain the OS version from the kif.xml file located at $EPOCROOT/epoc32/data/kif.xml.
+
+	If successful, the function returns a string such as "v95" to indicate 9.5; None is
+	returned if for any reason the function cannot determine the OS version."""
+
+	releaseTagName = "ki:release"
+	osVersion = None
+
+	import xml.dom.minidom
+
+	try:
+		# Parsed document object
+		kifDom = xml.dom.minidom.parse(str(aPathToKifXml))
+
+		# elements - the elements whose names are releaseTagName
+		elements = kifDom.getElementsByTagName(releaseTagName)
+
+		# There should be exactly one of the elements whose name is releaseTagName
+		# If more than one, osVersion is left as None, since the version should be
+		# unique to the kif.xml file
+		if len(elements) == 1:
+			osVersionTemp = elements[0].getAttribute("version")
+			osVersion = "v" + osVersionTemp.replace(".", "")
+
+		kifDom.unlink() # Clean up
+
+	except:
+		# There's no documentation on which exceptions are raised by these functions.
+		# We catch everything and assume any exception means there was a failure to
+		# determine OS version. None is returned, and the code will fall back
+		# to looking at the buildinfo.txt file.
+		pass
+
+	return osVersion
+
+def getOsVerFromBuildInfoTxt(aPathToBuildInfoTxt):
+	"""Obtain the OS version from the buildinfo.txt file located at $EPOCROOT/epoc32/data/buildinfo.txt.
+
+	If successful, the function returns a string such as "v95" to indicate 9.5; None is
+	returned if for any reason the function cannot determine the OS version.
+
+	The file $EPOCROOT/epoc32/data/buildinfo.txt is presumed to exist. The client code should
+	handle existance/non-existance."""
+
+	pathToBuildInfoTxt = str(aPathToBuildInfoTxt) # String form version of path to buildinfo.txt
+
+	# Open the file for reading; throw an exception if it could not be read - note that
+	# it should exist at this point.
+	try:
+		buildInfoTxt = open(pathToBuildInfoTxt)
+	except IOError, (number, message):
+		raise MetaDataError("Could not read buildinfo.txt file at" + pathToBuildInfoTxt + ": (" + message + ")")
+
+	# Example buildinfo.txt contents:
+	#
+	# DeviceFamily               100
+	# DeviceFamilyRev            0x900
+	# ManufacturerSoftwareBuild  M08765_Symbian_OS_v9.5
+	#
+	# Regexp to match the line containing the OS version
+	# Need to match things like M08765_Symbian_OS_v9.5 and M08765_Symbian_OS_vFuture
+	# So for the version, match everything except whitespace after v. Whitespace
+	# signifies the end of the regexp.
+	osVersionMatcher = re.compile('.*_Symbian_OS_v([^\s]*)', re.I)
+	osVersion = None
+
+	# Search for a regexp match over all the times in the file
+	# Note: if two or more lines match the search pattern then
+	# the latest match will overwrite the osVersion string.
+	for line in buildInfoTxt:
+		matchResult = osVersionMatcher.match(line)
+		if matchResult:
+			result = matchResult.groups()
+			osVersion = "v" +  str(reduce(lambda x, y: x + y, result))
+			osVersion = osVersion.replace(".", "")
+
+	buildInfoTxt.close() # Clean-up
+
+	return osVersion
+
+def getBuildableBldInfBuildPlatforms(aBldInfBuildPlatforms,
+									aDefaultOSBuildPlatforms,
+									aBaseDefaultOSBuildPlatforms,
+									aBaseUserDefaultOSBuildPlatforms):
+	"""Obtain a set of build platform names supported by a bld.inf file
+
+	Build platform deduction is based on both the contents of the PRJ_PLATFORMS section of
+	a bld.inf file together with a hard-coded set of default build platforms supported by
+	the build system itself."""
+
+	expandedBldInfBuildPlatforms = []
+	removePlatforms = set()
+
+	for bldInfBuildPlatform in aBldInfBuildPlatforms:
+		if bldInfBuildPlatform.upper() == "DEFAULT":
+			expandedBldInfBuildPlatforms.extend(aDefaultOSBuildPlatforms.split())
+		elif bldInfBuildPlatform.upper() == "BASEDEFAULT":
+			expandedBldInfBuildPlatforms.extend(aBaseDefaultOSBuildPlatforms.split())
+		elif bldInfBuildPlatform.upper() == "BASEUSERDEFAULT":
+			expandedBldInfBuildPlatforms.extend(aBaseUserDefaultOSBuildPlatforms.split())
+		elif bldInfBuildPlatform.startswith("-"):
+			removePlatforms.add(bldInfBuildPlatform.lstrip("-").upper())
+		else:
+			expandedBldInfBuildPlatforms.append(bldInfBuildPlatform.upper())
+
+	if len(expandedBldInfBuildPlatforms) == 0:
+		expandedBldInfBuildPlatforms.extend(aDefaultOSBuildPlatforms.split())
+
+	# make a set of platforms that can be built
+	buildableBldInfBuildPlatforms = set(expandedBldInfBuildPlatforms)
+
+	# Add platforms that are buildable by virtue of the presence of another
+	for piggyBackedPlatform in PiggyBackedBuildPlatforms:
+		if piggyBackedPlatform in buildableBldInfBuildPlatforms:
+			buildableBldInfBuildPlatforms.update(PiggyBackedBuildPlatforms.get(piggyBackedPlatform))
+
+	# Remove platforms that were negated
+	buildableBldInfBuildPlatforms -= removePlatforms
+
+	return buildableBldInfBuildPlatforms
+
+
+def getPreProcessorCommentDetail (aPreProcessorComment):
+	"""Takes a preprocessor comment and returns an array containing the filename and linenumber detail."""
+
+	commentDetail = []
+	commentMatch = re.search('# (?P<LINENUMBER>\d+) "(?P<FILENAME>.*)"', aPreProcessorComment)
+
+	if commentMatch:
+		filename = commentMatch.group('FILENAME')
+		filename = os.path.abspath(filename)
+		filename = re.sub(r'\\\\', r'\\', filename)
+		filename = re.sub(r'//', r'/', filename)
+		filename = generic_path.Path(filename)
+		linenumber = int (commentMatch.group('LINENUMBER'))
+
+		commentDetail.append(filename)
+		commentDetail.append(linenumber)
+
+	return commentDetail
+
+
+def getSpecName(aFileRoot, fullPath=False):
+	"""Returns a build spec name: this is the file root (full path
+	or simple file name) made safe for use as a file name."""
+
+	if fullPath:
+		specName = str(aFileRoot).replace("/","_")
+		specName = specName.replace(":","")
+	else:
+		specName = aFileRoot.File()
+
+	return specName.lower()
+
+
+# Classes
+
+class MetaDataError(Exception):
+	"""Fatal error wrapper, to be thrown directly back to whatever is calling."""
+
+	def __init__(self, aText):
+		self.Text = aText
+	def __str__(self):
+		return repr(self.Text)
+
+
+class PreProcessedLine(str):
+	"""Custom string class that accepts filename and line number information from
+	a preprocessed context."""
+
+	def __new__(cls, value, *args, **keywargs):
+		return str.__new__(cls, value)
+
+	def __init__(self, value, aFilename, aLineNumber):
+		self.filename = aFilename
+		self.lineNumber = aLineNumber
+
+	def getFilename (self):
+		return self.filename
+
+	def getLineNumber (self):
+		return self.lineNumber
+
+class PreProcessor(raptor_utilities.ExternalTool):
+	"""Preprocessor wrapper suitable for Symbian metadata file processing."""
+
+	def __init__(self, aPreProcessor,
+				 aStaticOptions,
+				 aIncludeOption,
+				 aMacroOption,
+				 aPreIncludeOption,
+				 aRaptor):
+		raptor_utilities.ExternalTool.__init__(self, aPreProcessor)
+		self.__StaticOptions = aStaticOptions
+		self.__IncludeOption = aIncludeOption
+		self.__MacroOption = aMacroOption
+		self.__PreIncludeOption = aPreIncludeOption
+
+		self.filename = ""
+		self.__Macros = []
+		self.__IncludePaths = []
+		self.__PreIncludeFile = ""
+		self.raptor = aRaptor
+
+	def call(self, aArgs, sourcefilename):
+		""" Override call so that we can do our own error handling."""
+		tool = self._ExternalTool__Tool
+		commandline = tool + " " + aArgs + " " + str(sourcefilename)
+		try:
+			# the actual call differs between Windows and Unix
+			if raptor_utilities.getOSFileSystem() == "unix":
+				p = subprocess.Popen(commandline, \
+									 shell=True, bufsize=65535, \
+									 stdin=subprocess.PIPE, \
+									 stdout=subprocess.PIPE, \
+									 stderr=subprocess.PIPE, \
+									 close_fds=True)
+			else:
+				p = subprocess.Popen(commandline, \
+									 bufsize=65535, \
+									 stdin=subprocess.PIPE, \
+									 stdout=subprocess.PIPE, \
+									 stderr=subprocess.PIPE, \
+									 universal_newlines=True)
+
+			# run the command and wait for all the output
+			(self._ExternalTool__Output, errors) = p.communicate()
+
+			if self.raptor.debugOutput:
+				self.raptor.Debug("Preprocessing Start %s", str(sourcefilename))
+				self.raptor.Debug("Output:\n%s", self._ExternalTool__Output)
+				self.raptor.Debug("Errors:\n%s", errors)
+				self.raptor.Debug("Preprocessing End %s", str(sourcefilename))
+
+			incRE = re.compile("In file included from")
+			fromRE = re.compile(r"\s+from")
+			warningRE = re.compile("warning:|pasting.+token|from.+:")
+			remarkRE = re.compile("no newline at end of file|does not give a valid preprocessing token")
+
+			actualErr = False
+			if errors != "":
+				for error in errors.splitlines():
+					if incRE.search(error) or fromRE.search(error):
+						continue
+					if not remarkRE.search(error):
+						if warningRE.search(error):
+							self.raptor.Warn("%s: %s", tool, error)
+						else:
+							self.raptor.Error("%s: %s", tool, error)
+							actualErr = True
+			if actualErr:
+				raise MetaDataError("Errors in %s" % str(sourcefilename))
+
+		except Exception,e:
+			raise MetaDataError("Preprocessor exception: '%s' : in command : '%s'" % (str(e), commandline))
+
+		return 0	# all OK
+
+	def setMacros(self, aMacros):
+		self.__Macros = aMacros
+
+	def addMacro(self, aMacro):
+		self.__Macros.append(aMacro)
+
+	def addMacros(self, aMacros):
+		self.__Macros.extend(aMacros)
+
+	def getMacros(self):
+		return self.__Macros
+
+
+	def addIncludePath(self, aIncludePath):
+		p = str(aIncludePath)
+		if p == "":
+			self.raptor.Warn("attempt to set an empty preprocessor include path for %s" % str(self.filename))
+		else:
+			self.__IncludePaths.append(p)
+
+	def addIncludePaths(self, aIncludePaths):
+		for path in aIncludePaths:
+			self.addIncludePath(path)
+
+	def setIncludePaths(self, aIncludePaths):
+		self.__IncludePaths = []
+		self.addIncludePaths(aIncludePaths)
+
+	def setPreIncludeFile(self, aPreIncludeFile):
+		self.__PreIncludeFile = aPreIncludeFile
+
+	def preprocess(self):
+		preProcessorCall = self.__constructPreProcessorCall()
+		returnValue = self.call(preProcessorCall, self.filename)
+
+		return self.getOutput()
+
+	def __constructPreProcessorCall(self):
+
+		call = self.__StaticOptions
+
+		if self.__PreIncludeFile:
+			call += " " + self.__PreIncludeOption
+			call += " " + str(self.__PreIncludeFile)
+
+		for macro in self.__Macros:
+			call += " " + self.__MacroOption + macro
+
+		for includePath in self.__IncludePaths:
+			call += " " + self.__IncludeOption
+			call += " " + str(includePath)
+
+		return call
+
+
+class MetaDataFile(object):
+	"""A generic representation of a Symbian metadata file
+
+	Symbian metadata files are subject to preprocessing, primarily with macros based
+	on the selected build platform.  This class provides a generic means of wrapping
+	up the preprocessing of such files."""
+
+	def __init__(self, aFilename, gnucpp, depfiles, aRootLocation=None, log=None):
+		"""
+		@param aFilename	An MMP, bld.inf or other preprocessable build spec file
+		@param aDefaultPlatform  Default preprocessed version of this file
+		@param aCPP 		location of GNU CPP
+		@param depfiles     	list to add dependency file tuples to
+		@param aRootLocation    where the file is 
+		@param log 		A class with Debug(<string>), Info(<string>) and Error(<string>) methods
+		"""
+		self.filename = aFilename
+		self.__RootLocation = aRootLocation
+		# Dictionary with key of build platform and a text string of processed output as values
+		self.__PreProcessedContent = {}
+		self.log = log
+		self.depfiles = depfiles
+
+		self.__gnucpp = gnucpp
+		if gnucpp is None:
+			raise ValueError('gnucpp must be set')
+
+	def depspath(self, platform):
+	   """ Where does dependency information go relative to platform's SBS_BUILD_DIR?
+	       Subclasses should redefine this
+	   """
+	   return str(platform['SBS_BUILD_DIR']) + "/" + str(self.__RootLocation) + "." + platform['key_md5'] + ".d"
+
+	def getContent(self, aBuildPlatform):
+
+		key = aBuildPlatform['key']
+
+		config_macros = []
+
+		adepfilename = self.depspath(aBuildPlatform)
+		generateDepsOptions = ""
+		if adepfilename:
+
+			if raptor_utilities.getOSPlatform().startswith("win"):
+				metatarget = "$(PARSETARGET)"
+			else:
+				metatarget = "'$(PARSETARGET)'"
+			generateDepsOptions = "-MD -MF%s -MT%s" % (adepfilename, metatarget)
+			self.depfiles.append((adepfilename, metatarget))
+			try:
+				os.makedirs(os.path.dirname(adepfilename))
+			except Exception, e:
+				self.log.Debug("Couldn't make bldinf outputpath for dependency generation")
+
+		config_macros = (aBuildPlatform['PLATMACROS']).split()
+
+		if not key in self.__PreProcessedContent:
+
+			preProcessor = PreProcessor(self.__gnucpp, '-undef -nostdinc ' + generateDepsOptions + ' ',
+										'-I', '-D', '-include', self.log)
+			preProcessor.filename = self.filename
+
+			# always have the current directory on the include path
+			preProcessor.addIncludePath('.')
+
+			# the SYSTEMINCLUDE directories defined in the build config
+			# should be on the include path. This is added mainly to support
+			# Feature Variation as SYSTEMINCLUDE is usually empty at this point.
+			systemIncludes = aBuildPlatform['SYSTEMINCLUDE']
+			if systemIncludes:
+				preProcessor.addIncludePaths(systemIncludes.split())
+
+			preInclude = aBuildPlatform['VARIANT_HRH']
+
+			# for non-Feature Variant builds, the directory containing the HRH should
+			# be on the include path
+			if not aBuildPlatform['ISFEATUREVARIANT']:
+				preProcessor.addIncludePath(preInclude.Dir())
+
+			# and EPOCROOT/epoc32/include
+			preProcessor.addIncludePath(aBuildPlatform['EPOCROOT'].Append('epoc32/include'))
+
+			# and the directory containing the bld.inf file
+			if self.__RootLocation is not None and str(self.__RootLocation) != "":
+				preProcessor.addIncludePath(self.__RootLocation)
+
+			# and the directory containing the file we are processing
+			preProcessor.addIncludePath(self.filename.Dir())
+
+			# there is always a pre-include file
+			preProcessor.setPreIncludeFile(preInclude)
+
+			macros = ["SBSV2"]
+
+			if config_macros:
+				macros.extend(config_macros)
+
+			if macros:
+				for macro in macros:
+					preProcessor.addMacro(macro + "=_____" +macro)
+
+			# extra "raw" macros that do not need protecting
+			preProcessor.addMacro("__GNUC__=3")
+
+			preProcessorOutput = preProcessor.preprocess()
+
+			# Resurrect preprocessing replacements
+			pattern = r'([\\|/]| |) ?_____(('+macros[0]+')'
+			for macro in macros[1:]:
+				pattern += r'|('+macro+r')'
+
+			pattern += r'\s*)'
+			# Work on all Macros in one substitution.
+			text = re.sub(pattern, r"\1\2", preProcessorOutput)
+			text = re.sub(r"\n[\t ]*", r"\n", text)
+
+			self.__PreProcessedContent[key] = text
+
+		return self.__PreProcessedContent[key]
+
+class MMPFile(MetaDataFile):
+	"""A generic representation of a Symbian metadata file
+
+	Symbian metadata files are subject to preprocessing, primarily with macros based
+	on the selected build platform.  This class provides a generic means of wrapping
+	up the preprocessing of such files."""
+
+	def __init__(self, aFilename, gnucpp, bldinf, depfiles, log=None):
+		"""
+		@param aFilename	An MMP, bld.inf or other preprocessable build spec file
+		@param gnucpp 		location of GNU CPP
+		@param bldinf		the bld.inf file this mmp was specified in
+		@param depfiles         list to fill with mmp dependency files
+		@param log 		A class with Debug(<string>), Info(<string>) and Error(<string>) methods
+		"""
+		super(MMPFile, self).__init__(aFilename, gnucpp, depfiles, str(bldinf.filename.Dir()),  log)
+		self.__bldinf = bldinf
+		self.depfiles = depfiles
+
+		self.__gnucpp = gnucpp
+		if gnucpp is None:
+			raise ValueError('gnucpp must be set')
+
+	def depspath(self, platform):
+	   """ Where does dependency information go relative to platform's SBS_BUILD_DIR?
+	       Subclasses should redefine this
+	   """
+	   return self.__bldinf.outputpath(platform) + "/" + self.filename.File() + '.' + platform['key_md5'] + ".d"
+
+class Export(object):
+	"""Single processed PRJ_EXPORTS or PRJ_TESTEXPORTS entry from a bld.inf file"""
+
+	def getPossiblyQuotedStrings(cls,spec):
+		""" 	Split a string based on whitespace
+			but keep double quoted substrings together.
+		"""
+		inquotes=False
+		intokengap=False
+		sourcedest=[]
+		word = 0
+		for c in spec:
+			if c == '"':
+				if inquotes:
+					inquotes = False
+					word += 1
+					intokengap = True
+				else:
+					inquotes = True
+					intokengap = False
+				pass
+			elif c == ' ' or c == '\t':
+				if inquotes:
+					if len(sourcedest) == word:
+						sourcedest.append(c)
+					else:
+						sourcedest[word] += c
+				else:
+					if intokengap:
+						# gobble unquoted spaces
+						pass
+					else:
+						word += 1
+						intokengap=True
+				pass
+			else:
+				intokengap = False
+				if len(sourcedest) == word:
+					sourcedest.append(c)
+				else:
+					sourcedest[word] += c
+
+		return sourcedest
+
+	getPossiblyQuotedStrings = classmethod(getPossiblyQuotedStrings)
+
+
+	def __init__(self, aBldInfFile, aExportsLine, aType):
+		"""
+		Rules from the OS library for convenience:
+
+		For PRJ_TESTEXPORTS
+		source_file_1 [destination_file]
+		source_file_n [destination_file]
+		If the source file is listed with a relative path, the path will
+	 	  be considered relative to the directory containing the bld.inf file.
+		If a destination file is not specified, the source file will be copied
+		  to the directory containing the bld.inf file.
+		If a relative path is specified with the destination file, the path
+		  will be considered relative to directory containing the bld.inf file.
+
+		For PRJ_EXPORTS
+		source_file_1 [destination_file]
+		source_file_n [destination_file]
+		:zip zip_file [destination_path]
+
+		Note that:
+		If a source file is listed with a relative path, the path will be
+		considered relative to the directory containing the bld.inf file.
+
+		If a destination file is not specified, the source file will be copied
+		to epoc32\include\.
+
+		If a destination file is specified with the relative path, the path will
+		be considered relative to directory epoc32\include\.
+
+		If a destination begins with a drive letter, then the file is copied to
+		epoc32\data\<drive_letter>\<path>. For example,
+
+			mydata.dat e:\appdata\mydata.dat
+			copies mydata.dat to epoc32\data\e\appdata\mydata.dat.
+			You can use any driveletter between A and Z.
+
+		A line can start with the preface :zip. This instructs the build tools
+		to unzip the specified zip file to the specified destination path. If a
+		destination path is not specified, the source file will be unzipped in
+		the root directory.
+
+
+		"""
+
+		# Work out what action is required - unzip or copy?
+		action = "copy"
+		typematch = re.match(r'^\s*(?P<type>:zip\s+)?(?P<spec>[^\s].*[^\s])\s*$',aExportsLine, re.I)
+
+		spec = typematch.group('spec')
+		if spec == None:
+			raise ValueError('must specify at least a source file for an export')
+
+		if typematch.group('type') is not None:
+			action = "unzip"
+
+		# Split the spec into source and destination but take care
+		# to allow filenames with quoted strings.
+		exportEntries = Export.getPossiblyQuotedStrings(spec)
+
+		# Get the source path as specified by the bld.inf
+		source_spec = exportEntries.pop(0).replace(' ','%20')
+
+		# Resolve the source file
+		sourcepath = generic_path.Path(raptor_utilities.resolveSymbianPath(str(aBldInfFile), source_spec))
+
+		# Find it if the case of the filename is wrong:
+		# Carry on even if we don't find it
+		foundfile = sourcepath.FindCaseless()
+		if foundfile != None:
+			source = str(foundfile).replace(' ','%20')
+		else:
+			source = str(sourcepath).replace(' ','%20')
+
+
+		# Get the destination path as specified by the bld.inf
+		if len(exportEntries) > 0:
+			dest_spec = exportEntries.pop(0).replace(' ','%20')
+		else:
+			dest_spec = None
+		# Destination list - list of destinations. For the WINSCW resource building stage,
+		# files exported to the emulated drives and there are several locations, for example,
+		# PRJ_[TEST]EXPORTS
+		# 1234ABCD.SPD		z:/private/10009876/policy/1234ABCD.spd
+		# needs to end up copied in
+		# epoc32/data/z/private/10009876/policy/1234ABCD.spd *and* in
+		# epoc32/release/winscw/udeb/z/private/10009876/policy/1234ABCD.spd *and* in
+		# epoc32/release/winscw/urel/z/private/10009876/policy/1234ABCD.spd
+		dest_list = []
+
+		# Resolve the destination if one is specified
+		if dest_spec:
+			# check for troublesome characters
+			if ':' in dest_spec and not re.search('^[a-z]:', dest_spec, re.I):
+				raise ValueError("invalid filename " + dest_spec)
+
+			dest_spec = dest_spec.replace(' ','%20')
+			aSubType=""
+			if action == "unzip":
+				aSubType=":zip"
+				dest_spec = dest_spec.rstrip("\\/")
+
+			# Get the export destination(s) - note this can be a list of strings or just a string.
+			dest_list = raptor_utilities.resolveSymbianPath(str(aBldInfFile), dest_spec, aType, aSubType)
+
+			def process_dest(aDest):
+				if dest_spec.endswith('/') or  dest_spec.endswith('\\'):
+					m = generic_path.Path(source)
+					aDest += '/'+m.File()
+				return aDest
+
+			if isinstance(dest_list, list):
+				# Process each file in the list
+				dest_list = map(process_dest, dest_list)
+			else:
+				# Process the single destination
+				dest_list = process_dest(dest_list)
+
+		else:
+			# No destination was specified so we assume an appropriate one
+
+			dest_filename=generic_path.Path(source).File()
+
+			if aType == "PRJ_EXPORTS":
+				if action == "copy":
+					destination = '$(EPOCROOT)/epoc32/include/'+dest_filename
+				elif action == "unzip":
+					destination = '$(EPOCROOT)'
+			elif aType == "PRJ_TESTEXPORTS":
+				d = aBldInfFile.Dir()
+				if action == "copy":
+					destination = str(d.Append(dest_filename))
+				elif action == "unzip":
+					destination = "$(EPOCROOT)"
+			else:
+				raise ValueError("Export type should be 'PRJ_EXPORTS' or 'PRJ_TESTEXPORTS'. It was: "+str(aType))
+
+
+		self.__Source = source
+		if len(dest_list) > 0: # If the list has length > 0, this means there are several export destinations.
+			self.__Destination = dest_list
+		else: # Otherwise the list has length zero, so there is only a single export destination.
+			self.__Destination = destination
+		self.__Action = action
+
+	def getSource(self):
+		return self.__Source
+
+	def getDestination(self):
+		return self.__Destination # Note that this could be either a list, or a string, depending on the export destination
+
+	def getAction(self):
+		return self.__Action
+
+class ExtensionmakefileEntry(object):
+	def __init__(self, aGnuLine, aBldInfFile, tmp):
+
+		self.__BldInfFile = aBldInfFile
+		bldInfLocation = self.__BldInfFile.Dir()
+		biloc = str(bldInfLocation)
+		extInfLocation = tmp.filename.Dir()
+		eiloc = str(extInfLocation)
+
+		if eiloc is None or eiloc == "":
+			eiloc="." # Someone building with a relative raptor path
+		if biloc is None or biloc == "":
+			biloc="." # Someone building with a relative raptor path
+
+		self.__StandardVariables = {}
+		# Relative step-down to the root - let's try ignoring this for now, as it
+		# should amount to the same thing in a world where absolute paths are king
+		self.__StandardVariables['TO_ROOT'] = ""
+		# Top-level bld.inf location
+		self.__StandardVariables['TO_BLDINF'] = biloc
+		self.__StandardVariables['EXTENSION_ROOT'] = eiloc
+
+		# Get the directory and filename from the full path containing the extension makefile
+		self.__FullPath = generic_path.Join(eiloc,aGnuLine)
+		self.__FullPath = self.__FullPath.GetLocalString()
+		self.__Filename = os.path.split(self.__FullPath)[1]
+		self.__Directory = os.path.split(self.__FullPath)[0]
+
+	def getMakefileName(self):
+		return self.__Filename
+
+	def getMakeDirectory(self):
+		return self.__Directory
+
+	def getStandardVariables(self):
+		return self.__StandardVariables
+
+class Extension(object):
+	"""Single processed PRJ_EXTENSIONS or PRJ_TESTEXTENSIONS START EXTENSIONS...END block
+	from a bld.inf file"""
+
+	def __init__(self, aBldInfFile, aStartLine, aOptionLines, aBuildPlatform, aRaptor):
+		self.__BldInfFile = aBldInfFile
+		self.__Options = {}
+		self.interface = ""
+		self.__Raptor = aRaptor
+
+		makefile = ""
+		makefileMatch = re.search(r'^\s*START EXTENSION\s+(?P<MAKEFILE>\S+)\s*(?P<NAMETAG>\S*)$', aStartLine, re.I)
+
+		self.__RawMakefile = ""
+
+		if (makefileMatch):
+			self.__RawMakefile = makefileMatch.group('MAKEFILE')
+			self.nametag = makefileMatch.group('NAMETAG').lower()
+
+			# Ensure all \'s are translated into /'s if required
+			self.interface = self.__RawMakefile
+			self.interface = self.interface.replace("\\", "/").replace("/", ".")
+
+		# To support standalone testing, '$(' prefixed TEMs  are assumed to  start with
+		# a makefile variable and hence be fully located in FLM operation
+		if self.__RawMakefile.startswith("$("):
+			self.__Makefile = self.__RawMakefile + ".mk"
+		else:
+			self.__Makefile = '$(MAKEFILE_TEMPLATES)/' + self.__RawMakefile + ".mk"
+
+		for optionLine in aOptionLines:
+			optionMatch = re.search(r'^\s*(OPTION\s+)?(?P<VARIABLE>\S+)\s+(?P<VALUE>\S+.*)$',optionLine, re.I)
+			if optionMatch:
+				self.__Options[optionMatch.group('VARIABLE').upper()] = optionMatch.group('VALUE')
+
+		bldInfLocation = self.__BldInfFile.Dir()
+
+		biloc = str(bldInfLocation)
+		if biloc is None or biloc == "":
+			biloc="." # Someone building with a relative raptor path
+
+		extInfLocation = aStartLine.filename.Dir()
+
+		eiloc = str(extInfLocation)
+		if eiloc is None or eiloc == "":
+			eiloc="." # Someone building with a relative raptor path
+
+		self.__StandardVariables = {}
+		# Relative step-down to the root - let's try ignoring this for now, as it
+		# should amount to the same thing in a world where absolute paths are king
+		self.__StandardVariables['TO_ROOT'] = ""
+		# Top-level bld.inf location
+		self.__StandardVariables['TO_BLDINF'] = biloc
+		# Location of bld.inf file containing the current EXTENSION block
+		self.__StandardVariables['EXTENSION_ROOT'] = eiloc
+
+		# If the interface exists, this means it's not a Template Extension Makefile so don't look for a .meta file for it;
+		# so do nothing if it's not a template extension makefile
+		try:
+			self.__Raptor.cache.FindNamedInterface(str(self.interface), aBuildPlatform['CACHEID'])
+		except KeyError: # This means that this Raptor doesn't have the interface self.interface, so we are in a TEM
+			# Read extension meta file and get default options from it.  The use of TEM meta file is compulsory if TEM is used
+			metaFilename = "%s/epoc32/tools/makefile_templates/%s.meta" % (aBuildPlatform['EPOCROOT'], self.__RawMakefile)
+			metaFile = None
+			try:
+				metaFile = open(metaFilename, "r")
+			except IOError, e:
+				self.__warn("Extension: %s - cannot open Meta file: %s" % (self.__RawMakefile, metaFilename))
+
+			if metaFile:
+				for line in metaFile.readlines():
+					defaultOptionMatch = re.search(r'^OPTION\s+(?P<VARIABLE>\S+)\s+(?P<VALUE>\S+.*)$',line, re.I)
+					if defaultOptionMatch and defaultOptionMatch.group('VARIABLE').upper() not in self.__Options.keys():
+						self.__Options[defaultOptionMatch.group('VARIABLE').upper()] = defaultOptionMatch.group('VALUE')
+
+				metaFile.close()
+
+	def __warn(self, format, *extras):
+		if (self.__Raptor):
+			self.__Raptor.Warn(format, *extras)
+
+	def getIdentifier(self):
+		return re.sub (r'\\|\/|\$|\(|\)', '_', self.__RawMakefile)
+
+	def getMakefile(self):
+		return self.__Makefile
+
+	def getOptions(self):
+		return self.__Options
+
+	def getStandardVariables(self):
+		return self.__StandardVariables
+
+class MMPFileEntry(object):
+	def __init__(self, aFilename, aTestOption, aARMOption):
+		self.filename = aFilename
+		self.testoption = aTestOption
+		if aARMOption:
+			self.armoption = True
+		else:
+			self.armoption = False
+
+
+class BldInfFile(MetaDataFile):
+	"""Representation of a Symbian bld.inf file"""
+
+	def __init__(self, aFilename, gnucpp, depfiles, log=None):
+		MetaDataFile.__init__(self, aFilename, gnucpp, depfiles, None, log)
+		self.__Raptor = log
+		self.testManual = 0
+		self.testAuto = 0
+	# Generic
+
+	def getBuildPlatforms(self, aBuildPlatform):
+		platformList = []
+
+		for platformLine in self.__getSection(aBuildPlatform, 'PRJ_PLATFORMS'):
+			for platformEntry in platformLine.split():
+				platformList.append(platformEntry)
+
+		return platformList
+
+	# Build Platform Specific
+	def getMMPList(self, aBuildPlatform, aType="PRJ_MMPFILES"):
+		mmpFileList=[]
+		gnuList = []
+		makefileList = []
+		extFound = False
+		m = None
+
+		hashValue = {'mmpFileList': [] , 'gnuList': [], 'makefileList' : []}
+
+		for mmpFileEntry in self.__getSection(aBuildPlatform, aType):
+
+			actualBldInfRoot = mmpFileEntry.getFilename()
+			n = re.match('\s*(?P<makefiletype>(GNUMAKEFILE|N?MAKEFILE))\s+(?P<extmakefile>[^ ]+)\s*(support|manual)?\s*(?P<invalid>\S+.*)?\s*$',mmpFileEntry,re.I)
+			if n:
+
+				if (n.groupdict()['invalid']):
+					self.log.Error("%s (%d) : invalid .mmp file qualifier \"%s\"", mmpFileEntry.filename, mmpFileEntry.getLineNumber(), n.groupdict()['invalid'])
+				if raptor_utilities.getOSFileSystem() == "unix":
+					self.log.Warn("NMAKEFILE/GNUMAKEFILE/MAKEFILE keywords not supported on Linux")
+				else:
+					extmakefilearg = n.groupdict()['extmakefile']
+					bldInfDir = actualBldInfRoot.Dir()
+					extmakefilename = bldInfDir.Append(extmakefilearg)
+					extmakefile = ExtensionmakefileEntry(extmakefilearg, self.filename, mmpFileEntry)
+
+					if (n.groupdict()['makefiletype']).upper() == "GNUMAKEFILE":
+						gnuList.append(extmakefile)
+					else:
+						makefileList.append(extmakefile)
+			else:
+				# Currently there is only one possible option - build as arm.
+				# For TESTMMPFILES, the supported options are support, tidy, ignore, manual and build as arm
+				if aType.upper()=="PRJ_TESTMMPFILES":
+					if re.match('\s*(?P<name>[^ ]+)\s*(?P<baa>build_as_arm)?\s*(?P<support>support)?\s*(?P<ignore>ignore)?\s*(?P<tidy>tidy)?\s*(?P<manual>manual)?\s*(?P<invalid>\S+.*)?\s*$', mmpFileEntry, re.I):
+						m = re.match('\s*(?P<name>[^ ]+)\s*(?P<baa>build_as_arm)?\s*(?P<support>support)?\s*(?P<ignore>ignore)?\s*(?P<tidy>tidy)?\s*(?P<manual>manual)?\s*(?P<invalid>\S+.*)?\s*$', mmpFileEntry, re.I)
+				else:
+					if re.match('\s*(?P<name>[^ ]+)\s*(?P<baa>build_as_arm)?\s*(?P<invalid>\S+.*)?\s*$', mmpFileEntry, re.I):
+						m = re.match('\s*(?P<name>[^ ]+)\s*(?P<baa>build_as_arm)?\s*(?P<invalid>\S+.*)?\s*$', mmpFileEntry, re.I)
+
+			if m:
+				if (m.groupdict()['invalid']):
+					self.log.Error("%s (%d) : invalid .mmp file qualifier \"%s\"", mmpFileEntry.filename, mmpFileEntry.getLineNumber(), m.groupdict()['invalid'])
+
+				mmpFileName = m.groupdict()['name']
+				testmmpoption = "auto" # Setup tests to be automatic by default
+				tokens = m.groupdict()
+				for key,item in tokens.iteritems():
+					if key=="manual" and item=="manual":
+						testmmpoption = "manual"
+					elif key=="support" and item=="support":
+						testmmpoption = "support"
+					elif key=="ignore" and item=="ignore":
+						testmmpoption = "ignore"
+
+				buildasarm = False
+				if  m.groupdict()['baa']:
+					if m.groupdict()['baa'].lower() == 'build_as_arm':
+						buildasarm = True
+
+				if not mmpFileName.lower().endswith('.mmp'):
+					mmpFileName += '.mmp'
+				bldInfDir = actualBldInfRoot.Dir()
+				try:
+					mmpFileName = bldInfDir.Append(mmpFileName)
+					mmpfe = MMPFileEntry(mmpFileName, testmmpoption, buildasarm)
+					mmpFileList.append(mmpfe)
+				except ValueError, e:
+					self.log.Error("invalid .mmp file name: %s" % str(e))
+
+				m = None
+
+
+		hashValue['mmpFileList'] = mmpFileList
+		hashValue['gnuList'] = gnuList
+		hashValue['makefileList'] = makefileList
+
+		return hashValue
+
+	# Return a list of gnumakefiles used in the bld.inf
+	def getExtensionmakefileList(self, aBuildPlatform, aType="PRJ_MMPFILES",aString = ""):
+		extMakefileList=[]
+		m = None
+		for extmakeFileEntry in self.__getSection(aBuildPlatform, aType):
+
+			actualBldInfRoot = extmakeFileEntry.filename
+			if aType.upper()=="PRJ_TESTMMPFILES":
+				m = re.match('\s*GNUMAKEFILE\s+(?P<extmakefile>[^ ]+)\s*(?P<support>support)?\s*(?P<ignore>ignore)?\s*(?P<tidy>tidy)?\s*(?P<manual>manual)?\s*(?P<invalid>\S+.*)?\s*$',extmakeFileEntry,re.I)
+			else:
+				if aString == "gnumakefile":
+					m = re.match('\s*GNUMAKEFILE\s+(?P<extmakefile>[^ ]+)\s*(?P<invalid>\S+.*)?\s*$',extmakeFileEntry,re.I)
+				elif aString == "nmakefile":
+					m = re.match('\s*NMAKEFILE\s+(?P<extmakefile>[^ ]+)\s*(?P<invalid>\S+.*)?\s*$',extmakeFileEntry,re.I)
+				elif aString == "makefile":
+					m = re.match('\s*MAKEFILE\s+(?P<extmakefile>[^ ]+)\s*(?P<invalid>\S+.*)?\s*$',extmakeFileEntry,re.I)
+			if m:
+				if (m.groupdict()['invalid']):
+					self.log.Error("%s (%d) : invalid extension makefile qualifier \"%s\"", extmakeFileEntry.filename, extmakeFileEntry.getLineNumber(), m.groupdict()['invalid'])
+
+				extmakefilearg = m.groupdict()['extmakefile']
+				bldInfDir = actualBldInfRoot.Dir()
+				extmakefilename = bldInfDir.Append(extmakefilearg)
+				extmakefile = ExtensionmakefileEntry(extmakefilearg, self.filename, extmakeFileEntry)
+				extMakefileList.append(extmakefile)
+				m = None
+
+		return extMakefileList
+
+	def getTestExtensionmakefileList(self,aBuildPlatform,aString=""):
+		return self.getExtensionmakefileList(aBuildPlatform,"PRJ_TESTMMPFILES",aString)
+
+	def getTestMMPList(self, aBuildPlatform):
+		return self.getMMPList(aBuildPlatform, "PRJ_TESTMMPFILES")
+
+	def getRomTestType(self, aBuildPlatform):
+		testMMPList = self.getTestMMPList(aBuildPlatform)
+		for testMMPFileEntry in testMMPList['mmpFileList']:
+			if aBuildPlatform["TESTCODE"]:
+				# Calculate test type (manual or auto)
+				if testMMPFileEntry.testoption == "manual":
+					self.testManual += 1
+				if not (testMMPFileEntry.testoption == "support" or testMMPFileEntry.testoption == "manual" or testMMPFileEntry.testoption == "ignore"):
+					self.testAuto += 1
+		if self.testManual and self.testAuto:
+			return 'BOTH'
+		elif self.testAuto:
+			return 'AUTO'
+		elif self.testManual:
+			return 'MANUAL'
+		else:
+			return 'NONE'
+
+	def getExports(self, aBuildPlatform, aType="PRJ_EXPORTS"):
+		exportList = []
+
+		for exportLine in self.__getSection(aBuildPlatform, aType):
+
+			if not re.match(r'\S+', exportLine):
+				continue
+
+			try:
+				exportList.append(Export(exportLine.getFilename(), exportLine, aType))
+			except ValueError,e:
+				self.log.Error(str(e))
+
+		return exportList
+
+	def getTestExports(self, aBuildPlatform):
+		return self.getExports(aBuildPlatform, "PRJ_TESTEXPORTS")
+
+	def getExtensions(self, aBuildPlatform, aType="PRJ_EXTENSIONS"):
+		extensionObjects = []
+		start = ""
+		options = []
+
+		for extensionLine in self.__getSection(aBuildPlatform, aType):
+			if (re.search(r'^\s*START ',extensionLine, re.I)):
+				start = extensionLine
+			elif re.search(r'^\s*END\s*$',extensionLine, re.I):
+				if start == "":
+					self.log.Error("unmatched END statement in %s section", aType, bldinf=str(self.filename))
+				else:
+					extensionObjects.append(Extension(self.filename, start, options, aBuildPlatform, self.__Raptor))
+					start = ""
+					options = []
+			elif re.search(r'^\s*$',extensionLine, re.I):
+				continue
+			elif start:
+				options.append(extensionLine)
+
+		return extensionObjects
+
+	def getTestExtensions(self, aBuildPlatform):
+		return self.getExtensions(aBuildPlatform, "PRJ_TESTEXTENSIONS")
+
+	def __getSection(self, aBuildPlatform, aSection):
+
+		activeSection = False
+		sectionContent = []
+		lineContent = re.split(r'\n', self.getContent(aBuildPlatform));
+
+		currentBldInfFile = self.filename
+		currentLineNumber = 0
+
+		for line in lineContent:
+			if line.startswith("#"):
+				commentDetail = getPreProcessorCommentDetail(line)
+				currentBldInfFile = commentDetail[0]
+				currentLineNumber = commentDetail[1]-1
+				continue
+
+			currentLineNumber += 1
+
+			if not re.match(r'.*\S+', line):
+				continue
+			elif re.match(r'\s*' + aSection + r'\s*$', line, re.I):
+				activeSection = True
+			elif re.match(r'\s*PRJ_\w+\s*$', line, re.I):
+				activeSection = False
+			elif activeSection:
+				sectionContent.append(PreProcessedLine(line, currentBldInfFile, currentLineNumber))
+
+		return sectionContent
+
+	@staticmethod
+	def outputPathFragment(bldinfpath):
+		"""Return a relative path that uniquely identifies this bldinf file
+		   whilst being short so that it can be appended to epoc32/build.
+		   The  build product of a particular bld.inf may be placed in here.
+		   This affects its TEMs and its MMPs"""
+
+		absroot_str = os.path.abspath(str(bldinfpath)).lower().replace("\\","/")
+
+		uniqueid = hashlib.md5()
+		uniqueid.update(absroot_str)
+
+		specnamecomponents = (re.sub("^[A-Za-z]:", "", absroot_str)).split('/') # split, removing any drive identifier (if present)
+
+		pathlist=[]
+		while len(specnamecomponents) > 0:
+			top = specnamecomponents.pop()
+			if top.endswith('.inf'):
+				continue
+			elif top == 'group':
+				continue
+			else:
+				pathlist = [top]
+				break
+
+		pathlist.append("c_"+uniqueid.hexdigest()[:16])
+		return "/".join(pathlist)
+
+	def outputpath(self, platform):
+		""" The full path where product from this bldinf is created."""
+		return str(platform['SBS_BUILD_DIR']) + "/" + BldInfFile.outputPathFragment(self.filename)
+
+	def depspath(self, platform):
+	   """ Where does dependency information go relative to platform's SBS_BUILD_DIR?
+	       Subclasses should redefine this
+	   """
+	   return self.outputpath(platform) + "/bldinf." + platform['key_md5'] + ".d"
+
+
+
+class MMPRaptorBackend(MMPBackend):
+	"""A parser "backend" for the MMP language
+
+	This is used to map recognised MMP syntax onto a buildspec """
+
+	# Support priorities, with case-fixed mappings for use
+	epoc32priorities = {
+		'low':'Low',
+		'background':'Background',
+		'foreground':'Foreground',
+		'high':'High',
+		'windowserver':'WindowServer',
+		'fileserver':'FileServer',
+		'realtimeserver':'RealTimeServer',
+		'supervisor':'SuperVisor'
+		}
+
+	# Known capability flags with associated bitwise operations
+	supportedCapabilities = {
+		'tcb':(1<<0),
+		'commdd':(1<<1),
+		'powermgmt':(1<<2),
+		'multimediadd':(1<<3),
+		'readdevicedata':(1<<4),
+		'writedevicedata':(1<<5),
+		'drm':(1<<6),
+		'trustedui':(1<<7),
+		'protserv':(1<<8),
+		'diskadmin':(1<<9),
+		'networkcontrol':(1<<10),
+		'allfiles':(1<<11),
+		'swevent':(1<<12),
+		'networkservices':(1<<13),
+		'localservices':(1<<14),
+		'readuserdata':(1<<15),
+		'writeuserdata':(1<<16),
+		'location':(1<<17),
+		'surroundingsdd':(1<<18),
+		'userenvironment':(1<<19),
+	# Old capability names have zero value
+		'root':0,
+		'mediadd':0,
+		'readsystemdata':0,
+		'writesystemdata':0,
+		'sounddd':0,
+		'uidd':0,
+		'killanyprocess':0,
+		'devman':0,
+		'phonenetwork':0,
+		'localnetwork':0
+	  	}
+
+	library_re = re.compile(r"^(?P<name>[^{]+?)(?P<version>{(?P<major>[0-9]+)\.(?P<minor>[0-9]+)})?(\.(lib|dso))?$",re.I)
+
+
+	def __init__(self, aRaptor, aMmpfilename, aBldInfFilename):
+		super(MMPRaptorBackend,self).__init__()
+		self.platformblock = None
+		self.__Raptor = aRaptor
+		self.__debug("-----+++++ %s " % aMmpfilename)
+		self.BuildVariant = raptor_data.Variant(name = "mmp")
+		self.ApplyVariants = []
+		self.ResourceVariants = []
+		self.BitmapVariants = []
+		self.StringTableVariants = []
+		self.__bldInfFilename = aBldInfFilename
+		self.__targettype = "UNKNOWN"
+		self.__currentMmpFile = aMmpfilename
+		self.__defFileRoot = self.__currentMmpFile
+		self.__currentLineNumber = 0
+		self.__sourcepath = raptor_utilities.resolveSymbianPath(self.__currentMmpFile, "")
+		self.__userinclude = ""
+		self.__systeminclude = ""
+		self.__bitmapSourcepath = self.__sourcepath
+		self.__current_resource = ""
+		self.__resourceFiles = []
+		self.__pageConflict = []
+		self.__debuggable = ""
+		self.__compressionKeyword = ""
+		self.sources = []
+		self.capabilities = []
+
+		self.__TARGET = ""
+		self.__TARGETEXT = ""
+		self.deffile = ""
+		self.__LINKAS = ""
+		self.nostrictdef = False
+		self.featureVariant = False
+
+		self.__currentResourceVariant = None
+		self.__currentStringTableVariant = None
+		self.__explicitversion = False
+		self.__versionhex = ""
+
+		# "ALL" capability calculated based on the total capabilities currently supported
+		allCapabilities = 0
+		for supportedCapability in MMPRaptorBackend.supportedCapabilities.keys():
+			allCapabilities = allCapabilities | MMPRaptorBackend.supportedCapabilities[supportedCapability]
+		MMPRaptorBackend.supportedCapabilities['all'] = allCapabilities
+
+	# Permit unit-testing output without a Raptor context
+	def __debug(self, format, *extras):
+		if (self.__Raptor):
+			self.__Raptor.Debug(format, *extras)
+
+	def __warn(self, format, *extras):
+		if (self.__Raptor):
+			self.__Raptor.Warn(format, *extras)
+
+	def doPreProcessorComment(self,s,loc,toks):
+		commentDetail = getPreProcessorCommentDetail(toks[0])
+		self.__currentMmpFile = commentDetail[0].GetLocalString()
+		self.__currentLineNumber = commentDetail[1]
+		self.__debug("Current file %s, line number %s\n"  % (self.__currentMmpFile,str(self.__currentLineNumber)))
+		return "OK"
+
+	def doBlankLine(self,s,loc,toks):
+		self.__currentLineNumber += 1
+
+	def doStartPlatform(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		self.__debug( "Start Platform block "+toks[0])
+		self.platformblock = toks[0]
+		return "OK"
+
+	def doEndPlatform(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		self.__debug( "Finalise platform " + self.platformblock)
+		return "OK"
+
+	def doSetSwitch(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		prefix=""
+		varname = toks[0].upper()
+
+		# A bright spark made the optionname the same as
+		# the env variable. One will override the other if we pass this
+		# on to make.  Add a prefix to prevent the clash.
+		if varname=='ARMINC':
+			prefix="SET_"
+			self.__debug( "Set switch "+toks[0]+" ON")
+			self.BuildVariant.AddOperation(raptor_data.Set(prefix+varname, "1"))
+
+		elif varname=='NOSTRICTDEF':
+			self.nostrictdef = True
+			self.__debug( "Set switch "+toks[0]+" ON")
+			self.BuildVariant.AddOperation(raptor_data.Set(prefix+varname, "1"))
+
+		elif varname == 'PAGED':
+			self.BuildVariant.AddOperation(raptor_data.Set(varname, "1"))
+			self.__debug( "Set switch PAGE ON")
+			# PAGED is equivalent to PAGEDCODE
+			self.BuildVariant.AddOperation(raptor_data.Set("PAGEDCODE_OPTION", "paged"))
+			self.__debug( "Set switch PAGEDCODE ON")
+			self.__pageConflict.append("PAGEDCODE")
+
+		elif varname == 'UNPAGED':
+			self.BuildVariant.AddOperation(raptor_data.Set("PAGED", "0"))
+			self.__debug( "Set switch PAGED OFF")
+			# UNPAGED is equivalent to UNPAGEDCODE *and* UNPAGEDDATA
+			self.BuildVariant.AddOperation(raptor_data.Set("PAGEDCODE_OPTION", "unpaged"))
+			self.__debug( "Set switch PAGEDCODE OFF")
+			self.BuildVariant.AddOperation(raptor_data.Set("PAGEDDATA_OPTION", "unpaged"))
+			self.__debug( "Set data PAGEDDATA OFF")
+			self.__pageConflict.append("UNPAGEDCODE")
+			self.__pageConflict.append("UNPAGEDDATA")
+
+		elif varname == 'PAGEDCODE':
+			self.BuildVariant.AddOperation(raptor_data.Set("PAGEDCODE_OPTION", "paged"))
+			self.__debug( "Set switch " + varname + " ON")
+			self.__pageConflict.append(varname)
+
+		elif varname == 'PAGEDDATA':
+			self.BuildVariant.AddOperation(raptor_data.Set("PAGEDDATA_OPTION", "paged"))
+			self.__debug( "Set switch " + varname + " ON")
+			self.__pageConflict.append(varname)
+
+		elif varname == 'UNPAGEDCODE':
+			self.BuildVariant.AddOperation(raptor_data.Set("PAGEDCODE_OPTION", "unpaged"))
+			self.__debug( "Set switch " + varname + " ON")
+			self.__pageConflict.append(varname)
+			
+		elif varname == 'UNPAGEDDATA':
+			self.BuildVariant.AddOperation(raptor_data.Set("PAGEDDATA_OPTION", "unpaged"))
+			self.__debug( "Set switch " + varname + " ON")
+			self.__pageConflict.append(varname)
+
+		elif varname == 'NOLINKTIMECODEGENERATION':
+			self.BuildVariant.AddOperation(raptor_data.Set("LTCG",""))
+			self.__debug( "Set switch " + varname + " OFF")
+			
+		elif varname == 'NOMULTIFILECOMPILATION':
+			self.BuildVariant.AddOperation(raptor_data.Set("MULTIFILE_ENABLED",""))
+			self.__debug( "Set switch " + varname + " OFF")
+
+		elif varname == 'DEBUGGABLE':
+			if self.__debuggable != "udeb":
+				self.__debuggable = "udeb urel"
+			else:
+				self.__Raptor.Warn("DEBUGGABLE keyword ignored as DEBUGGABLE_UDEBONLY is already specified")
+		
+		elif varname == 'DEBUGGABLE_UDEBONLY':
+			if self.__debuggable != "":
+				self.__Raptor.Warn("DEBUGGABLE keyword has no effect as DEBUGGABLE or DEBUGGABLE_UDEBONLY is already set")
+			self.__debuggable = "udeb"
+		
+		elif varname == 'FEATUREVARIANT':
+			self.BuildVariant.AddOperation(raptor_data.Set(varname,"1"))
+			self.featureVariant = True
+		
+		elif varname in ['COMPRESSTARGET', 'NOCOMPRESSTARGET', 'INFLATECOMPRESSTARGET', 'BYTEPAIRCOMPRESSTARGET']:
+			self.resolveCompressionKeyword(varname)
+		
+		else:
+			self.__debug( "Set switch "+toks[0]+" ON")
+			self.BuildVariant.AddOperation(raptor_data.Set(prefix+varname, "1"))
+
+		return "OK"
+
+	def doAssignment(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		varname = toks[0].upper()
+		if varname=='TARGET':
+			(self.__TARGET, self.__TARGETEXT) = os.path.splitext(toks[1])
+			self.__TARGETEXT = self.__TARGETEXT.lstrip('.')
+
+			self.BuildVariant.AddOperation(raptor_data.Set("REQUESTEDTARGETEXT", self.__TARGETEXT.lower()))
+
+			lowercase_TARGET = self.__TARGET.lower()
+			self.__debug("Set "+toks[0]+" to " + lowercase_TARGET)
+			self.__debug("Set REQUESTEDTARGETEXT to " + self.__TARGETEXT.lower())
+
+			self.BuildVariant.AddOperation(raptor_data.Set("TARGET", self.__TARGET))
+			self.BuildVariant.AddOperation(raptor_data.Set("TARGET_lower", lowercase_TARGET))
+			if  lowercase_TARGET !=  self.__TARGET:
+				self.__debug("TARGET is not lowercase: '%s' - might cause BC problems." % self.__TARGET)
+		elif varname=='TARGETTYPE':
+			self.__debug("Set "+toks[0]+" to " + str(toks[1]))
+			self.__targettype=toks[1]
+			if  self.__targettype.lower() == "none":
+				self.BuildVariant.AddOperation(raptor_data.Set("TARGET", ""))
+				self.BuildVariant.AddOperation(raptor_data.Set("TARGET_lower",""))
+				self.BuildVariant.AddOperation(raptor_data.Set("REQUESTEDTARGETEXT", ""))
+			self.BuildVariant.AddOperation(raptor_data.Set(varname,toks[1].lower()))
+
+		elif varname=='TARGETPATH':
+			value = toks[1].lower().replace('\\','/')
+			self.__debug("Set "+varname+" to " + value)
+			self.BuildVariant.AddOperation(raptor_data.Set(varname, value))
+
+		elif varname=='OPTION' or varname=='LINKEROPTION':
+			self.__debug("Set "+toks[1]+varname+" to " + str(toks[2]))
+			self.BuildVariant.AddOperation(raptor_data.Append(varname+"_"+toks[1].upper()," ".join(toks[2])))
+
+			# Warn about OPTION ARMASM
+			if "armasm" in toks[1].lower():
+				self.__Raptor.Warn(varname+" ARMASM has no effect (use OPTION ARMCC).")
+
+		elif varname=='OPTION_REPLACE':
+			# Warn about OPTION_REPLACE ARMASM
+			if "armasm" in toks[1].lower():
+				self.__Raptor.Warn("OPTION_REPLACE ARMASM has no effect (use OPTION_REPLACE ARMCC).")
+			else:
+				args = " ".join(toks[2])
+
+				searchReplacePairs = self.resolveOptionReplace(args)
+
+				for searchReplacePair in searchReplacePairs:
+					self.__debug("Append %s to OPTION_REPLACE_%s", searchReplacePair, toks[1].upper())
+					self.BuildVariant.AddOperation(raptor_data.Append(varname+"_"+toks[1].upper(),searchReplacePair))
+
+		elif varname=='SYSTEMINCLUDE' or varname=='USERINCLUDE':
+			for path in toks[1]:
+				resolved = raptor_utilities.resolveSymbianPath(self.__currentMmpFile, path)
+				self.BuildVariant.AddOperation(raptor_data.Append(varname,resolved))
+
+				if varname=='SYSTEMINCLUDE':
+					self.__systeminclude += ' ' + resolved
+					self.__debug("  %s = %s",varname, self.__systeminclude)
+				else:
+					self.__userinclude += ' ' + resolved
+					self.__debug("  %s = %s",varname, self.__userinclude)
+
+				self.__debug("Appending %s to %s",resolved, varname)
+
+			self.__systeminclude = self.__systeminclude.strip()
+			self.__systeminclude = self.__systeminclude.rstrip('\/')
+			self.__userinclude = self.__userinclude.strip()
+			self.__userinclude = self.__userinclude.rstrip('\/')
+
+		elif varname=='EXPORTLIBRARY':
+			# Remove extension from the EXPORTLIBRARY name
+			libName = toks[1].rsplit(".", 1)[0]
+			self.__debug("Set "+varname+" to " + libName)
+			self.BuildVariant.AddOperation(raptor_data.Set(varname,"".join(libName)))
+
+		elif varname=='CAPABILITY':
+			for cap in toks[1]:
+				cap = cap.lower()
+				self.__debug("Setting  "+toks[0]+": " + cap)
+				if not cap.startswith("-"):
+					if not cap.startswith("+"):
+						cap = "+" + cap	
+				self.capabilities.append(cap)
+		elif varname=='DEFFILE':
+			self.__defFileRoot = self.__currentMmpFile
+			self.deffile = toks[1]
+		elif varname=='LINKAS':
+			self.__debug("Set "+toks[0]+"  OPTION to " + str(toks[1]))
+			self.__LINKAS = toks[1]
+			self.BuildVariant.AddOperation(raptor_data.Set(varname, toks[1]))
+		elif varname=='SECUREID' or varname=='VENDORID':
+			hexoutput = MMPRaptorBackend.canonicalUID(toks[1])
+			self.__debug("Set "+toks[0]+"  OPTION to " + hexoutput)
+			self.BuildVariant.AddOperation(raptor_data.Set(varname, hexoutput))
+		elif varname=='VERSION':
+			if toks[-1] == "EXPLICIT":
+				self.__explicitversion = True
+				self.BuildVariant.AddOperation(raptor_data.Set("EXPLICITVERSION", "1"))
+
+			vm = re.match(r'^(\d+)(\.(\d+))?$', toks[1])
+			if vm is not None:
+				version = vm.groups()
+				# the major version number
+				major = int(version[0],10)
+
+				# add in the minor number
+				minor = 0
+				if version[1] is not None:
+					minor = int(version[2],10)
+				else:
+					self.__Raptor.Warn("VERSION (%s) missing '.minor' in %s, using '.0'" % (toks[1],self.__currentMmpFile))
+
+				self.__versionhex = "%04x%04x" % (major, minor)
+				self.BuildVariant.AddOperation(raptor_data.Set(varname, "%d.%d" %(major, minor)))
+				self.BuildVariant.AddOperation(raptor_data.Set(varname+"HEX", self.__versionhex))
+				self.__debug("Set "+toks[0]+"  OPTION to " + toks[1])
+				self.__debug("Set "+toks[0]+"HEX OPTION to " + "%04x%04x" % (major,minor))
+
+			else:
+				self.__Raptor.Warn("Invalid version supplied to VERSION (%s), using default value" % toks[1])
+
+		elif varname=='EPOCHEAPSIZE':
+			# Standardise on sending hex numbers to the FLMS.
+
+			if toks[1].lower().startswith('0x'):
+				min = long(toks[1],16)
+			else:
+				min = long(toks[1],10)
+
+			if toks[2].lower().startswith('0x'):
+				max = long(toks[2],16)
+			else:
+				max = long(toks[2],10)
+
+			self.BuildVariant.AddOperation(raptor_data.Set(varname+"MIN", "%x" % min))
+			self.__debug("Set "+varname+"MIN  OPTION to '%x' (hex)" % min )
+			self.BuildVariant.AddOperation(raptor_data.Set(varname+"MAX", "%x" % max))
+			self.__debug("Set "+varname+"MAX  OPTION to '%x' (hex)" % max )
+
+			# Some toolchains require decimal versions of the min/max values, converted to KB and
+			# rounded up to the next 1KB boundary
+			min_dec_kb = (int(min) + 1023) / 1024
+			max_dec_kb = (int(max) + 1023) / 1024
+			self.BuildVariant.AddOperation(raptor_data.Set(varname+"MIN_DEC_KB", "%d" % min_dec_kb))
+			self.__debug("Set "+varname+"MIN  OPTION KB to '%d' (dec)" % min_dec_kb )
+			self.BuildVariant.AddOperation(raptor_data.Set(varname+"MAX_DEC_KB", "%d" % max_dec_kb))
+			self.__debug("Set "+varname+"MAX  OPTION KB to '%d' (dec)" % max_dec_kb )
+
+		elif varname=='EPOCSTACKSIZE':
+			if toks[1].lower().startswith('0x'):
+				stack = long(toks[1],16)
+			else:
+				stack = long(toks[1],10)
+			self.BuildVariant.AddOperation(raptor_data.Set(varname, "%x" % stack))
+			self.__debug("Set "+varname+"  OPTION to '%x' (hex)" % stack  )
+		elif varname=='EPOCPROCESSPRIORITY':
+			# low, background, foreground, high, windowserver, fileserver, realtimeserver or supervisor
+			# These are case insensitive in metadata entries, but must be mapped to a static case pattern for use
+			prio = toks[1].lower()
+
+			# NOTE: Original validation here didn't actually work.  This has been corrected to provide an error, but probably needs re-examination.
+			if not MMPRaptorBackend.epoc32priorities.has_key(prio):
+				self.__Raptor.Error("Priority setting '%s' is not a valid priority - should be one of %s.", prio, MMPRaptorBackend.epoc32priorities.values())
+			else:
+				self.__debug("Set "+toks[0]+" to " +  MMPRaptorBackend.epoc32priorities[prio])
+				self.BuildVariant.AddOperation(raptor_data.Set(varname,MMPRaptorBackend.epoc32priorities[prio]))
+		elif varname=='ROMTARGET' or varname=='RAMTARGET':
+			if len(toks) == 1:
+				self.__debug("Set "+toks[0]+" to <none>" )
+				self.BuildVariant.AddOperation(raptor_data.Set(varname,"<none>"))
+			else:
+				toks1 = str(toks[1]).replace("\\","/")
+				if toks1.find(","):
+					toks1 = re.sub("[,'\[\]]", "", toks1).replace("//","/")
+				self.__debug("Set "+toks[0]+" to " + toks1)
+				self.BuildVariant.AddOperation(raptor_data.Set(varname,toks1))
+		elif varname=='APPLY':
+			self.ApplyVariants.append(toks[1])
+		else:
+			self.__debug("Set "+toks[0]+" to " + str(toks[1]))
+			self.BuildVariant.AddOperation(raptor_data.Set(varname,"".join(toks[1])))
+
+			if varname=='LINKAS':
+				self.__LINKAS = toks[1]
+
+		return "OK"
+
+	def doAppend(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		"""MMP command
+		"""
+		name=toks[0].upper()
+		if len(toks) == 1:
+			# list can be empty e.g. MACRO _FRED_ when fred it defined in the HRH
+			# causes us to see just "MACRO" in the input - it is valid to ignore this
+			self.__debug("Empty append list for " + name)
+			return "OK"
+		self.__debug("Append to "+name+" the values: " +str(toks[1]))
+
+		if name=='MACRO':
+			name='MMPDEFS'
+		elif name=='LANG':
+			# don't break the environment variable
+			name='LANGUAGES'
+
+		for item in toks[1]:
+			if name=='MMPDEFS':
+				# Unquote any macros since the FLM does it anyhow
+				if item.startswith('"') and item.endswith('"') \
+				or item.startswith("'") and item.endswith("'"):
+					item = item.strip("'\"")
+			if name=='LIBRARY' or name=='DEBUGLIBRARY':
+				im = MMPRaptorBackend.library_re.match(item)
+				if not im:
+					self.__error("LIBRARY: %s Seems to have an invalid name.\nExpected xxxx.lib or xxxx.dso\n where xxxx might be\n\tname or \n\tname(n,m) where n is a major version number and m is a minor version number\n" %item)
+				d = im.groupdict()
+
+				item = d['name']
+				if d['version'] is not None:
+					item += "{%04x%04x}" % (int(d['major']), int(d['minor']))
+				item += ".dso"
+			elif name=='STATICLIBRARY':
+				# the FLM will decide on the ending appropriate to the platform
+				item = re.sub(r"^(.*)\.[Ll][Ii][Bb]$",r"\1", item)
+			elif name=="LANGUAGES":
+				item = item.lower()
+			elif (name=="WIN32_LIBRARY" and (item.startswith(".") or re.search(r'[\\|/]',item))) \
+				or (name=="WIN32_RESOURCE"):
+				# Relatively pathed win32 libraries, and all win32 resources, are resolved in relation
+				# to the wrapper bld.inf file in which their .mmp file is specified.  This equates to
+				# the current working directory in ABLD operation.
+				item = raptor_utilities.resolveSymbianPath(self.__bldInfFilename, item)
+				
+			self.BuildVariant.AddOperation(raptor_data.Append(name,item," "))
+			
+			# maintain a debug library list, the same as LIBRARY but with DEBUGLIBRARY values
+			# appended as they are encountered
+			if name=='LIBRARY' or name=='DEBUGLIBRARY':
+				self.BuildVariant.AddOperation(raptor_data.Append("LIBRARY_DEBUG",item," "))			
+
+		return "OK"
+
+	def canonicalUID(number):
+		""" convert a UID string into an 8 digit hexadecimal string without leading 0x """
+		if number.lower().startswith("0x"):
+			n = int(number,16)
+		else:
+			n = int(number,10)
+
+		return "%08x" % n
+
+	canonicalUID = staticmethod(canonicalUID)
+
+	def doUIDAssignment(self,s,loc,toks):
+		"""A single UID command results in a number of spec variables"""
+		self.__currentLineNumber += 1
+
+		hexoutput = MMPRaptorBackend.canonicalUID(toks[1][0])
+		self.__debug( "Set UID2 to %s" % hexoutput )
+		self.BuildVariant.AddOperation(raptor_data.Set("UID2", hexoutput))
+
+		if len(toks[1]) > 1:
+			hexoutput = MMPRaptorBackend.canonicalUID(toks[1][1])
+			self.__debug( "Set UID3 to %s" % hexoutput)
+			self.BuildVariant.AddOperation(raptor_data.Set("UID3", hexoutput))
+
+		self.__debug( "done set UID")
+		return "OK"
+
+	def doSourcePathAssignment(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		self.__sourcepath = raptor_utilities.resolveSymbianPath(self.__currentMmpFile, toks[1])
+		self.__debug( "Remembering self.sourcepath state:  "+str(toks[0])+" is now " + self.__sourcepath)
+		self.__debug("selfcurrentMmpFile: " + self.__currentMmpFile)
+		return "OK"
+
+
+	def doSourceAssignment(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		self.__debug( "Setting "+toks[0]+" to " + str(toks[1]))
+		for file in toks[1]:
+			# file is always relative to sourcepath but some MMP files
+			# have items that begin with a slash...
+			file = file.lstrip("/")
+			source = generic_path.Join(self.__sourcepath, file)
+
+			# If the SOURCEPATH itself begins with a '/', then dont look up the caseless version, since
+			# we don't know at this time what $(EPOCROOT) will evaluate to.
+			if source.GetLocalString().startswith('$(EPOCROOT)'):
+				self.sources.append(str(source))	
+				self.__debug("Append SOURCE " + str(source))
+
+			else:
+				foundsource = source.FindCaseless()
+				if foundsource == None:
+					# Hope that the file will be generated later
+					self.__debug("Sourcefile not found: %s" % source)
+					foundsource = source
+
+				self.sources.append(str(foundsource))	
+				self.__debug("Append SOURCE " + str(foundsource))
+
+
+		self.__debug("		sourcepath: " + self.__sourcepath)
+		return "OK"
+
+	# Resource
+
+	def doOldResourceAssignment(self,s,loc,toks):
+		# Technically deprecated, but still used, so...
+		self.__currentLineNumber += 1
+		self.__debug("Processing old-style "+toks[0]+" "+str(toks[1]))
+
+		sysRes = (toks[0].lower() == "systemresource")
+
+		for rss in toks[1]:
+			variant = raptor_data.Variant()
+
+			source = generic_path.Join(self.__sourcepath, rss)
+			variant.AddOperation(raptor_data.Set("SOURCE", str(source)))
+			self.__resourceFiles.append(str(source))
+
+			target = source.File().rsplit(".", 1)[0]	# remove the extension
+			variant.AddOperation(raptor_data.Set("TARGET", target))
+			variant.AddOperation(raptor_data.Set("TARGET_lower", target.lower()))
+
+			header = target.lower() + ".rsg"			# filename policy
+			variant.AddOperation(raptor_data.Set("HEADER", header))
+
+			if sysRes:
+				dsrtp = self.getDefaultSystemResourceTargetPath()
+				variant.AddOperation(raptor_data.Set("TARGETPATH", dsrtp))
+
+			self.ResourceVariants.append(variant)
+
+		return "OK"
+
+	def getDefaultSystemResourceTargetPath(self):
+		# the default systemresource TARGETPATH value should come from the
+		# configuration rather than being hard-coded here. Then again, this
+		# should really be deprecated away into oblivion...
+		return "system/data"
+
+
+	def getDefaultResourceTargetPath(self, targettype):
+		# the different default TARGETPATH values should come from the
+		# configuration rather than being hard-coded here.
+		if targettype in ["plugin", "plugin3"]:
+			return "resource/plugins"
+		if targettype == "pdl":
+			return "resource/printers"
+		return ""
+
+	def resolveOptionReplace(self, content):
+		"""
+		Constructs search/replace pairs based on .mmp OPTION_REPLACE entries for use on tool command lines
+		within FLMS.
+
+		Depending on what's supplied to OPTION_REPLACE <TOOL>, the core part of the <TOOL> command line
+		in the relevant FLM will have search and replace actions performed on it post-expansion (but pre-
+		any OPTION <TOOL> additions).
+
+		In terms of logic, we try to follow what ABLD does, as the current behaviour is undocumented.
+		What happens is a little inconsistent, and best described by some generic examples:
+
+			OPTION_REPLACE TOOL existing_option replacement_value
+
+				Replace all instances of "option existing_value" with "option replacement_value"
+
+			OPTION_REPLACE TOOL existing_option replacement_option
+
+				Replace all instances of "existing_option" with "replacement_option".
+
+			If "existing_option" is present in isolation then a removal is performed.
+
+		Any values encountered that don't follow an option are ignored.
+		Options are identified as being prefixed with either '-' or '--'.
+
+		The front-end processes each OPTION_REPLACE entry and then appends one or more search/replace pairs
+		to an OPTION_REPLACE_<TOOL> variable in the following format:
+
+		     search<->replace
+		"""
+		# Note that, for compatibility reasons, the following is mostly a port to Python of the corresponding
+		# ABLD Perl, and hence maintains ABLD's idiosyncrasies in what it achieves
+
+		searchReplacePairs = []
+		matches = re.findall("-{1,2}\S+\s*(?!-)\S*",content)
+
+		if matches:
+			# reverse so we can process as a stack whilst retaining original order
+			matches.reverse()
+
+			while (len(matches)):
+				match = matches.pop()
+
+				standaloneMatch = re.match('^(?P<option>\S+)\s+(?P<value>\S+)$', match)
+
+				if (standaloneMatch):
+					# Option listed standalone with a replacement value
+					# Example:
+					# 	OPTION_REPLACE ARMCC --cpu 6
+					# Intention:
+					# 	Replace instances of  "--cpu <something>" with "--cpu 6"
+
+					# Substitute any existing "option <existing_value>" instances with a single word
+					# "@@<existing_value>" for later replacement
+					searchReplacePairs.append('%s <->@@' % standaloneMatch.group('option'))
+
+					# Replace "@@<existing_value>" entries from above with "option <new_value>" entries
+					# A pattern substitution is used to cover pre-existing values
+					searchReplacePairs.append('@@%%<->%s %s' % (standaloneMatch.group('option'), standaloneMatch.group('value')))
+				else:
+					# Options specified in search/replace pairs with optional values
+					# Example:
+					#	OPTION_REPLACE ARMCC --O2 --O3
+					# Intention:
+					#	Replace instances of "--O2" with "--O3"
+
+					# At this point we will be looking at just the search option - there may or may not
+					# be a replacement to consider
+					search = match
+					replace = ""
+					if len(matches):
+						replace = matches.pop()
+
+					searchReplacePairs.append('%s<->%s' % (search, replace))
+
+			# Replace spaces to maintain word-based grouping in downstream makefile lists
+			for i in range(0,len(searchReplacePairs)):
+				searchReplacePairs[i] = searchReplacePairs[i].replace(' ','%20')
+
+		return searchReplacePairs
+
+	def doStartResource(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		self.__debug("Start RESOURCE "+toks[1])
+
+		self.__current_resource = generic_path.Path(self.__sourcepath, toks[1])
+		self.__current_resource = str(self.__current_resource)
+
+		self.__debug("sourcepath: " + self.__sourcepath)
+		self.__debug("self.__current_resource source: " + toks[1])
+		self.__debug("adjusted self.__current_resource source=" + self.__current_resource)
+
+		self.__currentResourceVariant = raptor_data.Variant()
+		self.__currentResourceVariant.AddOperation(raptor_data.Set("SOURCE", self.__current_resource))
+		self.__resourceFiles.append(self.__current_resource)
+
+		# The target name is the basename of the resource without the extension
+		# e.g. "/fred/129ab34f.rss" would have a target name of "129ab34f"
+		target = self.__current_resource.rsplit("/",1)[-1]
+		target = target.rsplit(".",1)[0]
+		self.__currentResourceVariant.AddOperation(raptor_data.Set("TARGET", target))
+		self.__currentResourceVariant.AddOperation(raptor_data.Set("TARGET_lower", target.lower()))
+		self.__headerspecified = False
+		self.__headeronlyspecified = False
+		self.__current_resource_header = target.lower() + ".rsg"
+
+		return "OK"
+
+	def doResourceAssignment(self,s,loc,toks):
+		""" Assign variables for resource files """
+		self.__currentLineNumber += 1
+		varname = toks[0].upper() # the mmp keyword
+		varvalue = "".join(toks[1])
+
+		# Get rid of any .rsc extension because the build system
+		# needs to have it stripped off to calculate other names
+		# for other purposes and # we aren't going to make it
+		# optional anyhow.
+		if varname == "TARGET":
+			target_withext = varvalue.rsplit("/\\",1)[-1]
+			target = target_withext.rsplit(".",1)[0]
+			self.__current_resource_header = target.lower() + ".rsg"
+			self.__currentResourceVariant.AddOperation(raptor_data.Set("TARGET_lower", target.lower()))
+			self.__debug("Set resource "+varname+" to " + target)
+			self.__currentResourceVariant.AddOperation(raptor_data.Set(varname,target))
+		if varname == "TARGETPATH":
+			varvalue=varvalue.replace('\\','/')
+			self.__debug("Set resource "+varname+" to " + varvalue)
+			self.__currentResourceVariant.AddOperation(raptor_data.Set(varname,varvalue))
+		else:
+			self.__debug("Set resource "+varname+" to " + varvalue)
+			self.__currentResourceVariant.AddOperation(raptor_data.Set(varname,varvalue))
+		return "OK"
+
+	def doResourceAppend(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		self.__debug("Append resource to "+toks[0]+" the values: " +str(toks[1]))
+		varname = toks[0].upper()
+
+		# we cannot use LANG as it interferes with the environment
+		if varname == "LANG":
+			varname = "LANGUAGES"
+
+		for item in toks[1]:
+			if varname == "LANGUAGES":
+				item = item.lower()
+			self.__currentResourceVariant.AddOperation(raptor_data.Append(varname,item))
+		return "OK"
+
+	def doResourceSetSwitch(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		name = toks[0].upper()
+
+		if name == "HEADER":
+			self.__headerspecified = True
+
+		elif name == "HEADERONLY":
+			self.__headeronlyspecified = True
+
+		else:
+			value = "1"
+			self.__debug( "Set resource switch " + name + " " + value)
+			self.__currentResourceVariant.AddOperation(raptor_data.Set(name, value))
+
+		return "OK"
+
+	def doEndResource(self,s,loc,toks):
+		self.__currentLineNumber += 1
+
+		# Header name can change, depening if there was a TARGET defined or not, so it must be appended at the end
+		if self.__headerspecified:
+			self.__debug("Set resource switch HEADER " + self.__current_resource_header)
+			self.__currentResourceVariant.AddOperation(raptor_data.Set("HEADER", self.__current_resource_header))
+
+		if self.__headeronlyspecified:
+			self.__debug("Set resource switch HEADERONLY " + self.__current_resource_header)
+			self.__currentResourceVariant.AddOperation(raptor_data.Set("HEADER", self.__current_resource_header))
+			self.__currentResourceVariant.AddOperation(raptor_data.Set("HEADERONLY", "True"))
+
+		self.__debug("End RESOURCE")
+		self.ResourceVariants.append(self.__currentResourceVariant)
+		self.__currentResourceVariant = None
+		self.__current_resource = ""
+		return "OK"
+
+	# Bitmap
+
+	def doStartBitmap(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		self.__debug("Start BITMAP "+toks[1])
+
+		self.__currentBitmapVariant = raptor_data.Variant(name = toks[1].replace('.','_'))
+		# Use BMTARGET and BMTARGET_lower because that prevents
+		# confusion with the TARGET and TARGET_lower of our parent MMP
+		# when setting the OUTPUTPATH.  This in turn allows us to
+		# not get tripped up by multiple mbms being generated with
+		# the same name to the same directory.
+		self.__currentBitmapVariant.AddOperation(raptor_data.Set("BMTARGET", toks[1]))
+		self.__currentBitmapVariant.AddOperation(raptor_data.Set("BMTARGET_lower", toks[1].lower()))
+		self.__currentBitmapVariant.AddOperation(raptor_data.Set("SOURCE", ""))
+		return "OK"
+
+	def doBitmapAssignment(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		self.__debug("Set bitmap "+toks[0]+" to " + str(toks[1]))
+		name = toks[0].upper()
+		value = "".join(toks[1])
+		if name == "TARGETPATH":
+			value = value.replace('\\','/')
+
+		self.__currentBitmapVariant.AddOperation(raptor_data.Set(name,value))
+		return "OK"
+
+	def doBitmapSourcePathAssignment(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		self.__debug("Previous bitmap sourcepath:" + self.__bitmapSourcepath)
+		self.__bitmapSourcepath = raptor_utilities.resolveSymbianPath(self.__currentMmpFile, toks[1])
+		self.__debug("New bitmap sourcepath: " + self.__bitmapSourcepath)
+
+	def doBitmapSourceAssignment(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		self.__debug( "Setting "+toks[0]+" to " + str(toks[1]))
+		# The first "source" is the colour depth for all the others.
+		# The depth format is b[,m] where b is the bitmap depth and m is
+		# the mask depth.
+		# Valid values for b are: 1 2 4 8 c4 c8 c12 c16 c24 c32 c32a (?)
+		# Valid values for m are: 1 8 (any number?)
+		#
+		# If m is specified then the bitmaps are in pairs: b0 m0 b1 m1...
+		# If m is not specified then there are no masks, just bitmaps: b0 b1...
+		colordepth = toks[1][0].lower()
+		if "," in colordepth:
+			(bitmapdepth, maskdepth) = colordepth.split(",")
+		else:
+			bitmapdepth = colordepth
+			maskdepth = 0
+
+		sources=""
+		mask = False
+		for file in toks[1][1:]:
+			path = generic_path.Join(self.__bitmapSourcepath, file)
+			if sources:
+				sources += " "
+			if mask:
+				sources += "DEPTH=" + maskdepth + " FILE=" + str(path)
+			else:
+				sources += "DEPTH=" + bitmapdepth + " FILE=" + str(path)
+			if maskdepth:
+				mask = not mask
+		self.__debug("sources: " + sources)
+		self.__currentBitmapVariant.AddOperation(raptor_data.Append("SOURCE", sources))
+		return "OK"
+
+	def doBitmapSetSwitch(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		self.__debug( "Set bitmap switch "+toks[0]+" ON")
+		self.__currentBitmapVariant.AddOperation(raptor_data.Set(toks[0].upper(), "1"))
+		return "OK"
+
+	def doEndBitmap(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		self.__bitmapSourcepath = self.__sourcepath
+		self.BitmapVariants.append(self.__currentBitmapVariant)
+		self.__currentBitmapVariant = None
+		self.__debug("End BITMAP")
+		return "OK"
+
+	# Stringtable
+
+	def doStartStringTable(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		self.__debug( "Start STRINGTABLE "+toks[1])
+
+		specstringtable = generic_path.Join(self.__sourcepath, toks[1])
+		uniqname = specstringtable.File().replace('.','_') # corrected, filename only
+		source = str(specstringtable.FindCaseless())
+
+		self.__debug("sourcepath: " + self.__sourcepath)
+		self.__debug("stringtable: " + toks[1])
+		self.__debug("adjusted stringtable source=" + source)
+
+		self.__currentStringTableVariant = raptor_data.Variant(name = uniqname)
+		self.__currentStringTableVariant.AddOperation(raptor_data.Set("SOURCE", source))
+		self.__currentStringTableVariant.AddOperation(raptor_data.Set("EXPORTPATH", ""))
+		self.__stringtableExported = False
+
+		# The target name by default is the name of the stringtable without the extension
+		# e.g. the stringtable "/fred/http.st" would have a default target name of "http"
+		stringtable_withext = specstringtable.File()
+		self.__stringtable = stringtable_withext.rsplit(".",1)[0].lower()
+		self.__currentStringTableVariant.AddOperation(raptor_data.Set("TARGET", self.__stringtable))
+
+		self.__stringtableHeaderonlyspecified = False
+
+		return "OK"
+
+	def doStringTableAssignment(self,s,loc,toks):
+		""" Assign variables for stringtables """
+		self.__currentLineNumber += 1
+		varname = toks[0].upper() # the mmp keyword
+		varvalue = "".join(toks[1])
+
+		# Get rid of any .rsc extension because the build system
+		# needs to have it stripped off to calculate other names
+		# for other purposes and # we aren't going to make it
+		# optional anyhow.
+		if varname == "EXPORTPATH":
+			finalvalue = raptor_utilities.resolveSymbianPath(self.__currentMmpFile, varvalue)
+			self.__stringtableExported = True
+		else:
+			finalvalue = varvalue
+
+		self.__debug("Set stringtable "+varname+" to " + finalvalue)
+		self.__currentStringTableVariant.AddOperation(raptor_data.Set(varname,finalvalue))
+		return "OK"
+
+	def doStringTableSetSwitch(self,s,loc,toks):
+		self.__currentLineNumber += 1
+		if toks[0].upper()== "HEADERONLY":
+			self.__stringtableHeaderonlyspecified = True
+			self.__debug( "Set stringtable switch "+toks[0]+" ON")
+			self.__currentStringTableVariant.AddOperation(raptor_data.Set(toks[0].upper(), "1"))
+		return "OK"
+
+	def doEndStringTable(self,s,loc,toks):
+		self.__currentLineNumber += 1
+
+		if not self.__stringtableExported:
+			# There was no EXPORTPATH specified for this stringtable
+			# so for our other code to be able to reference it we
+			# must add the path of the generated location to the userinclude path
+
+			ipath = "$(OUTPUTPATH)"
+			self.BuildVariant.AddOperation(raptor_data.Append("USERINCLUDE",ipath))
+			self.__userinclude += ' ' + ipath
+			self.__debug("  USERINCLUDE = %s", self.__userinclude)
+			self.__userinclude.strip()
+
+		self.StringTableVariants.append(self.__currentStringTableVariant)
+		self.__currentStringTableVariant = None
+		self.__debug("End STRINGTABLE")
+		if not self.__stringtableHeaderonlyspecified:
+			# Have to assume that this is where the cpp file will be.  This has to be maintained
+			# in sync with the FLM's idea of where this file should be.  We need a better way.
+			# Interfaces also need outputs that allow other interfaces to refer to their outputs
+			# without having to "know" where they will be.
+			self.sources.append('$(OUTPUTPATH)/' + self.__stringtable + '.cpp')
+		return "OK"
+
+
+	def doUnknownStatement(self,s,loc,toks):
+		self.__warn("%s (%d) : Unrecognised Keyword %s", self.__currentMmpFile, self.__currentLineNumber, str(toks))
+		self.__currentLineNumber += 1
+		return "OK"
+
+
+	def doUnknownBlock(self,s,loc,toks):
+		self.__warn("%s (%d) : Unrecognised Block %s", self.__currentMmpFile, self.__currentLineNumber, str(toks))
+		self.__currentLineNumber += 1
+		return "OK"
+
+	def doDeprecated(self,s,loc,toks):
+		self.__debug( "Deprecated command " + str(toks))
+		self.__warn("%s (%d) : %s is deprecated .mmp file syntax", self.__currentMmpFile, self.__currentLineNumber, str(toks))
+		self.__currentLineNumber += 1
+		return "OK"
+
+	def doNothing(self):
+		self.__currentLineNumber += 1
+		return "OK"
+
+	def finalise(self, aBuildPlatform):
+		"""Post-processing of data that is only applicable in the context of a fully
+		processed .mmp file."""
+		resolvedDefFile = ""
+
+		if self.__TARGET:
+			defaultRootName = self.__TARGET
+			if self.__TARGETEXT!="":
+				defaultRootName += "." + self.__TARGETEXT
+
+			# NOTE: Changing default .def file name based on the LINKAS argument is actually
+			# a defect, but this follows the behaviour of the current build system.
+			if (self.__LINKAS):
+				defaultRootName = self.__LINKAS
+
+			resolvedDefFile = self.resolveDefFile(defaultRootName, aBuildPlatform)
+			self.__debug("Resolved def file:  %s" % resolvedDefFile )
+			# We need to store this resolved deffile location for the FREEZE target
+			self.BuildVariant.AddOperation(raptor_data.Set("RESOLVED_DEFFILE", resolvedDefFile))
+
+		# If a deffile is specified, an FLM will put in a dependency.
+		# If a deffile is specified then raptor_meta will guess a name but:
+		#	1) If the guess is wrong then the FLM will complain "no rule to make ..."
+		#	2) In some cases, e.g. plugin, 1) is not desirable as the presence of a def file
+		#		is not a necessity.  In these cases the FLM needs to know if DEFFILE
+		#		is a guess or not so it can decide if a dependency should be added.
+
+		# We check that the def file exists and that it is non-zero (incredible
+		# that this should be needed).
+
+		deffile_keyword="1"
+		if self.deffile == "":
+			# If the user didn't specify a deffile name then
+			# we must be guessing
+			# Let's check if our guess actually corresponds to a
+			# real file.  If it does then that confims the guess.
+			#  If there's no file then we still need to pass make the name
+			# so it can complain about there not being a DEF file
+			# for this particular target type and fail to build this target.
+
+			deffile_keyword=""
+			try:
+				findpath = generic_path.Path(resolvedDefFile)
+				foundfile = findpath.FindCaseless()
+
+				if foundfile == None:
+					raise IOError("file not found")
+
+				self.__debug("Found DEFFILE  " + foundfile.GetLocalString())
+				rfstat = os.stat(foundfile.GetLocalString())
+
+				mode = rfstat[stat.ST_MODE]
+				if mode != None and stat.S_ISREG(mode) and rfstat[stat.ST_SIZE] > 0:
+					resolvedDefFile = str(foundfile)
+				else:
+					resolvedDefFile=""
+			except Exception,e:
+				self.__debug("While Searching for an IMPLIED  DEFFILE: %s: %s" % (str(e),str(findpath)) )
+				resolvedDefFile=""
+		else:
+			if not resolvedDefFile == "":
+				try:
+					findpath = generic_path.Path(resolvedDefFile)
+					resolvedDefFile = str(findpath.FindCaseless())
+					if resolvedDefFile=="None":
+						raise IOError("file not found")
+				except Exception,e:
+					self.__warn("While Searching for a SPECIFIED DEFFILE: %s: %s" % (str(e),str(findpath)) )
+					resolvedDefFile=""
+			else:
+				self.__warn("DEFFILE KEYWORD used (%s) but def file not resolved" % (self.deffile) )
+
+
+		self.BuildVariant.AddOperation(raptor_data.Set("DEFFILE", resolvedDefFile))
+		self.__debug("Set DEFFILE to " + resolvedDefFile)
+		self.BuildVariant.AddOperation(raptor_data.Set("DEFFILEKEYWORD", deffile_keyword))
+		self.__debug("Set DEFFILEKEYWORD to '%s'",deffile_keyword)
+
+		# If target type is "implib" it must have a def file
+		self.checkImplibDefFile(resolvedDefFile)
+
+		# if this target type has a default TARGETPATH other than "" for
+		# resources then we need to add that default to all resources which
+		# do not explicitly set the TARGETPATH themselves.
+		tp = self.getDefaultResourceTargetPath(self.getTargetType())
+		if tp:
+			for i,var in enumerate(self.ResourceVariants):
+				# does this resource specify its own TARGETPATH?
+				needTP = True
+				for op in var.ops:
+					if isinstance(op, raptor_data.Set) \
+					and op.name == "TARGETPATH":
+						needTP = False
+						break
+				if needTP:
+					self.ResourceVariants[i].AddOperation(raptor_data.Set("TARGETPATH", tp))
+
+		# some core build configurations need to know about the resource builds, and
+		# some resource building configurations need knowledge of the core build
+		for resourceFile in self.__resourceFiles:
+			self.BuildVariant.AddOperation(raptor_data.Append("RESOURCEFILES", resourceFile))
+
+		for i,var in enumerate(self.ResourceVariants):
+			self.ResourceVariants[i].AddOperation(raptor_data.Set("MAIN_TARGET_lower", self.__TARGET.lower()))
+			self.ResourceVariants[i].AddOperation(raptor_data.Set("MAIN_REQUESTEDTARGETEXT", self.__TARGETEXT.lower()))
+
+		# Create Capability variable in one SET operation (more efficient than multiple appends)
+		
+		self.BuildVariant.AddOperation(raptor_data.Set("CAPABILITY","".join(self.capabilities)))
+
+		# Resolve combined capabilities as hex flags, for configurations that require them
+		capabilityFlag1 = 0
+		capabilityFlag2 = 0			# Always 0
+
+		for capability in self.capabilities:
+			invert = 0
+
+			if capability.startswith('-'):
+				invert = 0xffffffff
+			capability = capability[1:]
+
+			if MMPRaptorBackend.supportedCapabilities.has_key(capability):
+				capabilityFlag1 = capabilityFlag1 ^ invert
+				capabilityFlag1 = capabilityFlag1 | MMPRaptorBackend.supportedCapabilities[capability]
+				capabilityFlag1 = capabilityFlag1 ^ invert
+
+		capabilityFlag1 = "%08xu" % capabilityFlag1
+		capabilityFlag2 = "%08xu" % capabilityFlag2
+
+		self.BuildVariant.AddOperation(raptor_data.Set("CAPABILITYFLAG1", capabilityFlag1))
+		self.__debug ("Set CAPABILITYFLAG1 to " + capabilityFlag1)
+		self.BuildVariant.AddOperation(raptor_data.Set("CAPABILITYFLAG2", capabilityFlag2))
+		self.__debug ("Set CAPABILITYFLAG2 to " + capabilityFlag2)
+
+		# For non-Feature Variant builds, the location of the product include hrh file is
+		# appended to the SYSTEMINCLUDE list
+		if not aBuildPlatform['ISFEATUREVARIANT']:
+			productIncludePath = str(aBuildPlatform['VARIANT_HRH'].Dir())
+			self.BuildVariant.AddOperation(raptor_data.Append("SYSTEMINCLUDE",productIncludePath))
+			self.__debug("Appending product include location %s to SYSTEMINCLUDE",productIncludePath)
+
+		# Specifying both a PAGED* and its opposite UNPAGED* keyword in a .mmp file
+		# will generate a warning and the last keyword specified will take effect.
+		self.__pageConflict.reverse()
+		if "PAGEDCODE" in self.__pageConflict and "UNPAGEDCODE" in self.__pageConflict:
+			for x in self.__pageConflict:
+				if x == "PAGEDCODE" or x == "UNPAGEDCODE":
+					self.__Raptor.Warn("Both PAGEDCODE and UNPAGEDCODE are specified. The last one %s will take effect" % x)
+					if x == "PAGEDCODE":
+						self.resolveCompressionKeyword("BYTEPAIRCOMPRESSTARGET")
+					break
+		elif "PAGEDCODE" in self.__pageConflict:
+			self.resolveCompressionKeyword("BYTEPAIRCOMPRESSTARGET")
+				
+		if "PAGEDDATA" in self.__pageConflict and "UNPAGEDDATA" in self.__pageConflict:
+			for x in self.__pageConflict:
+				if x == "PAGEDDATA" or x == "UNPAGEDDATA":
+					self.__Raptor.Warn("Both PAGEDDATA and UNPAGEDDATA are specified. The last one %s will take effect" % x)
+					if x == "PAGEDDATA":
+						self.resolveCompressionKeyword("BYTEPAIRCOMPRESSTARGET")
+					break
+		elif "PAGEDDATA" in self.__pageConflict:
+			self.resolveCompressionKeyword("BYTEPAIRCOMPRESSTARGET")
+
+		# Set Debuggable
+		self.BuildVariant.AddOperation(raptor_data.Set("DEBUGGABLE", self.__debuggable))
+
+		if self.__explicitversion:
+			self.BuildVariant.AddOperation(raptor_data.Append("UNIQUETARGETPATH","$(TARGET_lower)_$(VERSIONHEX)_$(REQUESTEDTARGETEXT)",'/'))
+		else:
+			self.BuildVariant.AddOperation(raptor_data.Append("UNIQUETARGETPATH","$(TARGET_lower)_$(REQUESTEDTARGETEXT)",'/'))
+
+		# Put the list of sourcefiles in with one Set operation - saves memory
+		# and performance over using multiple Append operations.
+		self.BuildVariant.AddOperation(raptor_data.Set("SOURCE",
+						   " ".join(self.sources)))
+
+	def getTargetType(self):
+		"""Target type in lower case - the standard format"""
+		return self.__targettype.lower()
+
+	def resolveCompressionKeyword(self, aCompressionKeyword):
+		"""If a compression keyword is set more than once either explicitly
+		or implicitly a warning is given and the last one takes effect 
+		"""
+		if self.__compressionKeyword and self.__compressionKeyword != aCompressionKeyword:
+			self.__Raptor.Warn("%s keyword in %s overrides earlier use of %s" % \
+						(aCompressionKeyword, self.__currentMmpFile, self.__compressionKeyword))
+			self.BuildVariant.AddOperation(raptor_data.Set(self.__compressionKeyword, ""))
+			self.__debug( "Set switch " + self.__compressionKeyword + " OFF")
+		self.BuildVariant.AddOperation(raptor_data.Set(aCompressionKeyword,"1"))
+		self.__debug( "Set switch " + aCompressionKeyword + " ON")
+		self.__compressionKeyword = aCompressionKeyword
+
+	def checkImplibDefFile(self, defFile):
+		"""Project with target type implib must have DEFFILE defined 
+		explicitly or implicitly, otherwise it is an error
+		""" 
+		if self.getTargetType() == 'implib' and defFile == '':
+			self.__Raptor.Error("No DEF File for IMPLIB target type in " + \
+							self.__currentMmpFile, bldinf=self.__bldInfFilename)
+
+	def resolveDefFile(self, aTARGET, aBuildPlatform):
+		"""Returns a fully resolved DEFFILE entry depending on .mmp file location and TARGET, DEFFILE and NOSTRICTDEF
+		entries in the .mmp file itself (where appropriate).
+		Is able to deal with target names that have multiple '.' characters e.g. messageintercept.esockdebug.dll
+		"""
+
+		resolvedDefFile = ""
+		platform = aBuildPlatform['PLATFORM']
+
+		# Not having a default .def file directory is a pretty strong indicator that
+		# .def files aren't supported for the particular platform
+		if PlatformDefaultDefFileDir.has_key(platform):
+			(targetname,targetext) = os.path.splitext(aTARGET)
+			(defname,defext) = os.path.splitext(self.deffile)
+			if defext=="":
+				defext = ".def"
+
+			# NOTE: WORKAROUND
+			if len(targetext) > 4:
+				targetname += defext
+
+			if not self.deffile:
+				resolvedDefFile = targetname
+			else:
+				if re.search('[\\|\/]$', self.deffile):
+					# If DEFFILE is *solely* a path, signified by ending in a slash, then TARGET is the
+					# basis for the default .def filename but with the specified path as prefix
+					resolvedDefFile = self.deffile + targetname
+
+				else:
+					resolvedDefFile = defname
+
+				resolvedDefFile = resolvedDefFile.replace('~', PlatformDefaultDefFileDir[platform])
+
+			if resolvedDefFile:
+				if not self.nostrictdef:
+					resolvedDefFile += 'u'
+
+				if self.__explicitversion:
+					resolvedDefFile += '{' + self.__versionhex + '}'
+
+				resolvedDefFile += defext
+
+
+				# If a DEFFILE statement doesn't specify a path in any shape or form, prepend the default .def file
+				# location based on the platform being built
+				if not re.search('[\\\/]+', self.deffile):
+					resolvedDefFile = '../'+PlatformDefaultDefFileDir[platform]+'/'+resolvedDefFile
+
+				resolvedDefFile = raptor_utilities.resolveSymbianPath(self.__defFileRoot, resolvedDefFile, 'DEFFILE', "", str(aBuildPlatform['EPOCROOT']))
+
+		return resolvedDefFile
+
+
+def CheckedGet(self, key, default = None):
+	"""extract a value from an self and raise an exception if None.
+
+	An optional default can be set to replace a None value.
+
+	This function belongs in the Evaluator class logically. But
+	Evaluator doesn't know how to raise a Metadata error. Since
+	being able to raise a metadata error is the whole point of
+	the method, it makes sense to adapt the Evaluator class from
+	raptor_meta for the use of everything inside raptor_meta.
+
+	... so it will be added to the Evaluator class.
+	"""
+
+	value = self.Get(key)
+	if value == None:
+		if default == None:
+			raise MetaDataError("configuration " + self.buildUnit.name +
+							    " has no variable " + key)
+		else:
+			return default
+	return value
+
+raptor_data.Evaluator.CheckedGet = CheckedGet 
+
+
+class MetaReader(object):
+	"""Entry point class for Symbian metadata processing.
+
+	Provides a means of integrating "traditional" Symbian metadata processing
+	with the new Raptor build system."""
+
+	filesplit_re = re.compile(r"^(?P<name>.*)\.(?P<ext>[^\.]*)$")
+
+	def __init__(self, aRaptor, configsToBuild):
+		self.__Raptor = aRaptor
+		self.BuildPlatforms = []
+		self.ExportPlatforms = []
+
+		# Get the version of CPP that we are using
+		metadata = self.__Raptor.cache.FindNamedVariant("meta")
+		evaluator = self.__Raptor.GetEvaluator(None, raptor_data.BuildUnit(metadata.name, [metadata]) )
+		self.__gnucpp = evaluator.CheckedGet("GNUCPP")
+		self.__defaultplatforms = evaluator.CheckedGet("DEFAULT_PLATFORMS")
+		self.__basedefaultplatforms = evaluator.CheckedGet("BASE_DEFAULT_PLATFORMS")
+		self.__baseuserdefaultplatforms = evaluator.CheckedGet("BASE_USER_DEFAULT_PLATFORMS")
+
+		# Only read each variant.cfg once
+		variantCfgs = {}
+
+		# Group the list of configurations into "build platforms".
+		# A build platform is a set of configurations which share
+		# the same metadata. In other words, a set of configurations
+		# for which the bld.inf and MMP files pre-process to exactly
+		# the same text.
+		platforms = {}
+
+		# Exports are not "platform dependent" but they are configuration
+		# dependent because different configs can have different EPOCROOT
+		# and VARIANT_HRH values. Each "build platform" has one associated
+		# "export platform" but several "build platforms" can be associated
+		# with the same "export platform".
+		exports = {}
+		
+		# We sort configurations by name here.  This is solely to deal with situations
+		# where macros linked to builds end up being used in preprocessor conditionals
+		# within bld.inf files that then wrap exports under PRJ_EXPORTS statements.
+		# Having exports that are conditional on these macros isn't supported, but
+		# as there are areas of the source base that make this assumption, and
+		# fail if emulator macros are used instead of arm ones, we ensure that arm
+		# configurations come first when multiple configurations are active, and so are
+		# used first for determining exports.
+		sortedConfigsToBuild = sorted(configsToBuild,key=lambda config: config.name)
+
+		self.__Raptor.Debug("MetaReader: sortedConfigsToBuild:  %s", [b.name for b in sortedConfigsToBuild])
+		for buildConfig in sortedConfigsToBuild:
+			# get everything we need to know about the configuration
+			evaluator = self.__Raptor.GetEvaluator(None, buildConfig)
+
+			detail = {}
+			detail['PLATFORM'] = evaluator.CheckedGet("TRADITIONAL_PLATFORM")
+			epocroot = evaluator.CheckedGet("EPOCROOT")
+			detail['EPOCROOT'] = generic_path.Path(epocroot)
+
+			sbs_build_dir = evaluator.CheckedGet("SBS_BUILD_DIR")
+			detail['SBS_BUILD_DIR'] = generic_path.Path(sbs_build_dir)
+			flm_export_dir = evaluator.CheckedGet("FLM_EXPORT_DIR")
+			detail['FLM_EXPORT_DIR'] = generic_path.Path(flm_export_dir)
+			detail['CACHEID'] = flm_export_dir
+			if raptor_utilities.getOSPlatform().startswith("win"):
+				detail['PLATMACROS'] = evaluator.CheckedGet("PLATMACROS.WINDOWS")
+			else:
+				detail['PLATMACROS'] = evaluator.CheckedGet("PLATMACROS.LINUX")
+
+			# Apply OS variant provided we are not ignoring this
+			if not self.__Raptor.ignoreOsDetection:
+				self.__Raptor.Debug("Automatic OS detection enabled.")
+				self.ApplyOSVariant(buildConfig, epocroot)
+			else: # We are ignore OS versions so no detection required, so no variant will be applied
+				self.__Raptor.Debug("Automatic OS detection disabled.")
+
+			# is this a feature variant config or an ordinary variant
+			fv = evaluator.Get("FEATUREVARIANTNAME")
+			if fv:
+				variantHdr = evaluator.CheckedGet("VARIANT_HRH")
+				variantHRH = generic_path.Path(variantHdr)
+				detail['ISFEATUREVARIANT'] = True
+			else:
+				variantCfg = evaluator.CheckedGet("VARIANT_CFG")
+				variantCfg = generic_path.Path(variantCfg)
+				if not variantCfg in variantCfgs:
+					# get VARIANT_HRH from the variant.cfg file
+					varCfg = getVariantCfgDetail(detail['EPOCROOT'], variantCfg)
+					variantCfgs[variantCfg] = varCfg['VARIANT_HRH']
+					# we expect to always build ABIv2
+					if not 'ENABLE_ABIV2_MODE' in varCfg:
+						self.__Raptor.Warn("missing flag ENABLE_ABIV2_MODE in %s file. ABIV1 builds are not supported.",
+										   str(variantCfg))
+				variantHRH = variantCfgs[variantCfg]
+				detail['ISFEATUREVARIANT'] = False
+
+			detail['VARIANT_HRH'] = variantHRH
+			self.__Raptor.Info("'%s' uses variant hrh file '%s'", buildConfig.name, variantHRH)
+			detail['SYSTEMINCLUDE'] = evaluator.CheckedGet("SYSTEMINCLUDE")
+
+
+			# find all the interface names we need
+			ifaceTypes = evaluator.CheckedGet("INTERFACE_TYPES")
+			interfaces = ifaceTypes.split()
+
+			for iface in interfaces:
+				detail[iface] = evaluator.CheckedGet("INTERFACE." + iface)
+
+			# not test code unless positively specified
+			detail['TESTCODE'] = evaluator.CheckedGet("TESTCODE", "")
+
+			# make a key that identifies this platform uniquely
+			# - used to tell us whether we have done the pre-processing
+			# we need already using another platform with compatible values.
+
+			key = str(detail['VARIANT_HRH']) \
+			 	+ str(detail['EPOCROOT']) \
+		    	+ detail['SYSTEMINCLUDE'] \
+		    	+ detail['PLATFORM'] \
+		    	+ detail['PLATMACROS']
+
+		    # Keep a short version of the key for use in filenames.
+			uniq = hashlib.md5()
+			uniq.update(key)
+
+			detail['key'] = key
+			detail['key_md5'] = "p_" + uniq.hexdigest()
+			del uniq
+
+			# compare this configuration to the ones we have already seen
+
+			# Is this an unseen export platform?
+			# concatenate all the values we care about in a fixed order
+			# and use that as a signature for the exports.
+			items = ['EPOCROOT', 'VARIANT_HRH', 'SYSTEMINCLUDE', 'TESTCODE', 'export']
+			export = ""
+			for i in  items:
+				if i in detail:
+					export += i + str(detail[i])
+
+			if export in exports:
+				# add this configuration to an existing export platform
+				index = exports[export]
+				self.ExportPlatforms[index]['configs'].append(buildConfig)
+			else:
+				# create a new export platform with this configuration
+				exports[export] = len(self.ExportPlatforms)
+				exp = copy.copy(detail)
+				exp['PLATFORM'] = 'EXPORT'
+				exp['configs']  = [buildConfig]
+				self.ExportPlatforms.append(exp)
+
+			# Is this an unseen build platform?
+			# concatenate all the values we care about in a fixed order
+			# and use that as a signature for the platform.
+			items = ['PLATFORM', 'PLATMACROS', 'EPOCROOT', 'VARIANT_HRH', 'SYSTEMINCLUDE', 'TESTCODE']
+
+			items.extend(interfaces)
+			platform = ""
+			for i in  items:
+				if i in detail:
+					platform += i + str(detail[i])
+
+			if platform in platforms:
+				# add this configuration to an existing build platform
+				index = platforms[platform]
+				self.BuildPlatforms[index]['configs'].append(buildConfig)
+			else:
+				# create a new build platform with this configuration
+				platforms[platform] = len(self.BuildPlatforms)
+				detail['configs'] = [buildConfig]
+				self.BuildPlatforms.append(detail)
+
+		# one platform is picked as the "default" for extracting things
+		# that are supposedly platform independent (e.g. PRJ_PLATFORMS)
+		self.defaultPlatform = self.ExportPlatforms[0]
+
+
+	def ReadBldInfFiles(self, aComponentList, doexport, dobuild = True):
+		"""Take a list of bld.inf files and return a list of build specs.
+
+		The returned specification nodes will be suitable for all the build
+		configurations under consideration (using Filter nodes where required).
+		"""
+
+		# we need a Filter node per export platform
+		exportNodes = []
+		for i,ep in enumerate(self.ExportPlatforms):
+			filter = raptor_data.Filter(name = "export_" + str(i))
+
+			# what configurations is this node active for?
+			for config in ep['configs']:
+				filter.AddConfigCondition(config.name)
+
+			exportNodes.append(filter)
+
+		# we need a Filter node per build platform
+		platformNodes = []
+		for i,bp in enumerate(self.BuildPlatforms):
+			filter = raptor_data.Filter(name = "build_" + str(i))
+
+			# what configurations is this node active for?
+			for config in bp['configs']:
+				filter.AddConfigCondition(config.name)
+
+			# platform-wide data
+			platformVar = raptor_data.Variant()
+			platformVar.AddOperation(raptor_data.Set("PRODUCT_INCLUDE",
+													 str(bp['VARIANT_HRH'])))
+
+			filter.AddVariant(platformVar)
+			platformNodes.append(filter)
+
+		# check that each bld.inf exists and add a Specification node for it
+		# to the nodes of the export and build platforms that it supports.
+		for c in aComponentList:
+			if c.bldinf_filename.isFile():
+				self.__Raptor.Info("Processing %s", str(c.bldinf_filename))
+				try:
+					self.AddComponentNodes(c, exportNodes, platformNodes)
+
+				except MetaDataError, e:
+					self.__Raptor.Error(e.Text, bldinf=str(c.bldinf_filename))
+					if not self.__Raptor.keepGoing:
+						return []
+			else:
+				self.__Raptor.Error("build info file does not exist", bldinf=str(c.bldinf_filename))
+				if not self.__Raptor.keepGoing:
+					return []
+
+		# now we have the top-level structure in place...
+		#
+		# <filter exports 1>
+		#		<spec bld.inf 1 />
+		#		<spec bld.inf 2 />
+		#		<spec bld.inf N /> </filter>
+		# <filter build 1>
+		#		<spec bld.inf 1 />
+		#		<spec bld.inf 2 />
+		#		<spec bld.inf N /> </filter>
+		# <filter build 2>
+		#		<spec bld.inf 1 />
+		#		<spec bld.inf 2 />
+		#		<spec bld.inf N /> </filter>
+		# <filter build 3>
+		#		<spec bld.inf 1 />
+		#		<spec bld.inf 2 />
+		#		<spec bld.inf N /> </filter>
+		#
+		# assuming that every bld.inf builds for every platform and all
+		# exports go to the same place. clearly, it is more likely that
+		# some filters have less than N child nodes. in bigger builds there
+		# will also be more than one export platform.
+
+		# we now need to process the EXPORTS for all the bld.inf nodes
+		# before we can do anything else (because raptor itself must do
+		# some exports before the MMP files that include them can be
+		# processed).
+		if doexport:
+			for i,p in enumerate(exportNodes):
+				exportPlatform = self.ExportPlatforms[i]
+				for s in p.GetChildSpecs():
+					try:
+						self.ProcessExports(s, exportPlatform)
+
+					except MetaDataError, e:
+						self.__Raptor.Error("%s",e.Text)
+						if not self.__Raptor.keepGoing:
+							return []
+		else:
+			self.__Raptor.Info("Not Processing Exports (--noexport enabled)")
+
+		# this is a switch to return the function at this point if export
+		# only option is specified in the run
+		if dobuild is not True:
+			self.__Raptor.Info("Processing Exports only")
+			return[]
+
+		# after exports are done we can look to see if there are any
+		# new Interfaces which can be used for EXTENSIONS. Make sure
+		# that we only load each cache once as some export platforms
+		# may share a directory.
+		doneID = {}
+		for ep in self.ExportPlatforms:
+			flmDir = ep["FLM_EXPORT_DIR"]
+			cid = ep["CACHEID"]
+			if flmDir.isDir() and not cid in doneID:
+				self.__Raptor.cache.Load(flmDir, cid)
+			doneID[cid] = True
+
+		# finally we can process all the other parts of the bld.inf nodes.
+		# Keep a list of the projects we were asked to build so that we can
+		# tell at the end if there were any we didn't know about.
+		self.projectList = list(self.__Raptor.projects)
+		for i,p in enumerate(platformNodes):
+			buildPlatform = self.BuildPlatforms[i]
+			for s in p.GetChildSpecs():
+				try:
+					self.ProcessTEMs(s, buildPlatform)
+					self.ProcessMMPs(s, buildPlatform)
+
+				except MetaDataError, e:
+					self.__Raptor.Error(e.Text)
+					if not self.__Raptor.keepGoing:
+						return []
+
+		for badProj in self.projectList:
+			self.__Raptor.Warn("Can't find project '%s' in any build info file", badProj)
+
+		# everything is specified
+		return exportNodes + platformNodes
+
+	def ModuleName(self,aBldInfPath):
+		"""Calculate the name of the ROM/emulator batch files that run the tests"""
+
+		def LeftPortionOf(pth,sep):
+			""" Internal function to return portion of str that is to the left of sep. 
+			The split is case-insensitive."""
+			length = len((pth.lower().split(sep.lower()))[0])
+			return pth[0:length]
+			
+		modulePath = LeftPortionOf(LeftPortionOf(os.path.dirname(aBldInfPath), "group"), "ongoing")
+		moduleName = os.path.basename(modulePath.strip("/"))
+		
+		# Ensure that ModuleName does not return blank, if the above calculation determines
+		# that moduleName is blank
+		if moduleName == "" or moduleName.endswith(":"):
+			moduleName = "module"
+		return moduleName
+
+
+	def AddComponentNodes(self, component, exportNodes, platformNodes):	
+		"""Add Specification nodes for a bld.inf to the appropriate platforms."""
+		bldInfFile = BldInfFile(component.bldinf_filename, self.__gnucpp, component.depfiles, self.__Raptor)
+		component.bldinf = bldInfFile 
+
+		specName = getSpecName(component.bldinf_filename, fullPath=True)
+
+		# exports are independent of build platform
+		for i,ep in enumerate(self.ExportPlatforms):
+			specNode = raptor_data.Specification(name = specName)
+
+			# keep the BldInfFile object for later
+			specNode.component = component
+
+			# add some basic data in a component-wide variant
+			var = raptor_data.Variant(name='component-wide')
+			var.AddOperation(raptor_data.Set("COMPONENT_META", str(component.bldinf_filename)))
+			var.AddOperation(raptor_data.Set("COMPONENT_NAME", component.componentname))
+			var.AddOperation(raptor_data.Set("COMPONENT_LAYER", component.layername))
+			specNode.AddVariant(var)
+
+			# add this bld.inf Specification to the export platform
+			exportNodes[i].AddChild(specNode)
+			component.exportspecs.append(specNode)
+
+		# get the relevant build platforms
+		listedPlatforms = bldInfFile.getBuildPlatforms(self.defaultPlatform)
+		platforms = getBuildableBldInfBuildPlatforms(listedPlatforms,
+								self.__defaultplatforms,
+								self.__basedefaultplatforms,
+								self.__baseuserdefaultplatforms)
+
+
+		outputDir = BldInfFile.outputPathFragment(component.bldinf_filename)
+
+		# Calculate "module name"
+		modulename = self.ModuleName(str(component.bldinf_filename))
+
+		for i,bp in enumerate(self.BuildPlatforms):
+			plat = bp['PLATFORM']
+			if bp['PLATFORM'] in platforms:
+				specNode = raptor_data.Specification(name = specName)
+
+				# remember what component this spec node comes from for later
+				specNode.component = component
+
+				# add some basic data in a component-wide variant
+				var = raptor_data.Variant(name='component-wide-settings-' + plat)
+				var.AddOperation(raptor_data.Set("COMPONENT_META",str(component.bldinf_filename)))
+				var.AddOperation(raptor_data.Set("COMPONENT_NAME", component.componentname))
+				var.AddOperation(raptor_data.Set("COMPONENT_LAYER", component.layername))
+				var.AddOperation(raptor_data.Set("MODULE", modulename))
+				var.AddOperation(raptor_data.Append("OUTPUTPATHOFFSET", outputDir, '/'))
+				var.AddOperation(raptor_data.Append("OUTPUTPATH", outputDir, '/'))
+				var.AddOperation(raptor_data.Append("BLDINF_OUTPUTPATH",outputDir, '/'))
+
+				var.AddOperation(raptor_data.Set("TEST_OPTION", component.bldinf.getRomTestType(bp)))
+				specNode.AddVariant(var)
+
+				# add this bld.inf Specification to the build platform
+				platformNodes[i].AddChild(specNode)
+				# also attach it into the component
+				component.specs.append(specNode)
+
+	def ProcessExports(self, componentNode, exportPlatform):
+		"""Do the exports for a given platform and skeleton bld.inf node.
+
+		This will actually perform exports as certain types of files (.mmh)
+		are required to be in place before the rest of the bld.inf node
+		(and parts of other bld.inf nodes) can be processed.
+
+		[some MMP files #include exported .mmh files]
+		"""
+		if exportPlatform["TESTCODE"]:
+			exports = componentNode.component.bldinf.getTestExports(exportPlatform)
+		else:
+			exports = componentNode.component.bldinf.getExports(exportPlatform)
+
+		self.__Raptor.Debug("%i exports for %s",
+							len(exports), str(componentNode.component.bldinf.filename))
+		if exports:
+
+			# each export is either a 'copy' or 'unzip'
+			# maybe we should trap multiple exports to the same location here?
+			epocroot = str(exportPlatform["EPOCROOT"])
+			bldinf_filename = str(componentNode.component.bldinf.filename)
+			exportwhatlog="<whatlog bldinf='%s' mmp='' config=''>\n" % bldinf_filename
+			for export in exports:
+				expSrc = export.getSource()
+				expDstList = export.getDestination() # Might not be a list in all circumstances
+
+				# make it a list if it isn't
+				if not isinstance(expDstList, list):
+					expDstList = [expDstList]
+
+				fromFile = generic_path.Path(expSrc.replace("$(EPOCROOT)", epocroot))
+
+				# For each destination in the destination list, add an export target, perform it if required.
+				# This ensures that make knows the dependency situation but that the export is made
+				# before any other part of the metadata requires it.  It also helps with the build
+				# from clean situation where we can't use order only prerequisites.
+				for expDst in expDstList:
+					toFile = generic_path.Path(expDst.replace("$(EPOCROOT)", epocroot))
+					try:
+						if export.getAction() == "copy":
+							# export the file
+							exportwhatlog += self.CopyExport(fromFile, toFile, bldinf_filename)
+						else:
+							members = self.UnzipExport(fromFile, toFile,
+									str(exportPlatform['SBS_BUILD_DIR']),
+									bldinf_filename)
+							
+							exportwhatlog += ("<archive zipfile='" + str(fromFile) + "'>\n")
+							if members != None:
+								exportwhatlog += members
+							exportwhatlog += "</archive>\n"
+					except MetaDataError, e:
+						if self.__Raptor.keepGoing:
+							self.__Raptor.Error("%s",e.Text, bldinf=bldinf_filename)
+						else:
+							raise e
+			exportwhatlog+="</whatlog>\n"
+			self.__Raptor.PrintXML("%s",exportwhatlog)
+
+	def CopyExport(self, _source, _destination, bldInfFile):
+		"""Copy the source file to the destination file (create a directory
+		   to copy into if it does not exist). Don't copy if the destination
+		   file exists and has an equal or newer modification time."""
+		source = generic_path.Path(str(_source).replace('%20',' '))
+		destination = generic_path.Path(str(_destination).replace('%20',' '))
+		dest_str = str(destination)
+		source_str = str(source)
+
+		exportwhatlog="<export destination='" + dest_str + "' source='" + \
+				source_str + "'/>\n"
+
+		try:
+
+
+			destDir = destination.Dir()
+			if not destDir.isDir():
+				os.makedirs(str(destDir))
+				shutil.copyfile(source_str, dest_str)
+				return exportwhatlog
+
+			sourceMTime = 0
+			destMTime = 0
+			sourceStat = 0
+			try:
+				sourceStat = os.stat(source_str)
+				sourceMTime = sourceStat[stat.ST_MTIME]
+				destMTime = os.stat(dest_str)[stat.ST_MTIME]
+			except OSError, e:
+				if sourceMTime == 0:
+					message = "Source of export does not exist:  " + str(source)
+					if not self.__Raptor.keepGoing:
+						raise MetaDataError(message)
+					else:
+						self.__Raptor.Error(message, bldinf=bldInfFile)
+
+			if destMTime == 0 or destMTime < sourceMTime:
+				if os.path.exists(dest_str):
+					os.chmod(dest_str,stat.S_IREAD | stat.S_IWRITE)
+				shutil.copyfile(source_str, dest_str)
+
+				# Ensure that the destination file remains executable if the source was also:
+				os.chmod(dest_str,sourceStat[stat.ST_MODE] | stat.S_IREAD | stat.S_IWRITE | stat.S_IWGRP ) 
+				self.__Raptor.Info("Copied %s to %s", source_str, dest_str)
+			else:
+				self.__Raptor.Info("Up-to-date: %s", dest_str)
+
+
+		except Exception,e:
+			message = "Could not export " + source_str + " to " + dest_str + " : " + str(e)
+			if not self.__Raptor.keepGoing:
+				raise MetaDataError(message)
+			else:
+				self.__Raptor.Error(message, bldinf=bldInfFile)
+
+		return exportwhatlog
+
+
+	def UnzipExport(self, _source, _destination, _sbs_build_dir, bldinf_filename):
+		"""Unzip the source zipfile into the destination directory
+		   but only if the markerfile does not already exist there
+		   or it does exist but is older than the zipfile.
+		   the markerfile is comprised of the name of the zipfile
+		   with the ".zip" removed and ".unzipped" added.
+		"""
+
+		# Insert spaces into file if they are there
+		source = str(_source).replace('%20',' ')
+		destination = str(_destination).replace('%20',' ')
+		sanitisedSource = raptor_utilities.sanitise(source)
+		sanitisedDestination = raptor_utilities.sanitise(destination)
+
+		destination = str(_destination).replace('%20',' ')
+		exportwhatlog = ""
+
+
+		try:
+			if not _destination.isDir():
+				os.makedirs(destination)
+
+			# Form the directory to contain the unzipped marker files, and make the directory if require.
+			markerfiledir = generic_path.Path(_sbs_build_dir)
+			if not markerfiledir.isDir():
+				os.makedirs(str(markerfiledir))
+
+			# Form the marker file name and convert to Python string
+			markerfilename = str(generic_path.Join(markerfiledir, sanitisedSource + sanitisedDestination + ".unzipped"))
+
+			# Don't unzip if the marker file is already there or more uptodate
+			sourceMTime = 0
+			destMTime = 0
+			try:
+				sourceMTime = os.stat(source)[stat.ST_MTIME]
+				destMTime = os.stat(markerfilename)[stat.ST_MTIME]
+			except OSError, e:
+				if sourceMTime == 0:
+					raise MetaDataError("Source zip for export does not exist:  " + source)
+			if destMTime != 0 and destMTime >= sourceMTime:
+				# This file has already been unzipped. Print members then return
+				exportzip = zipfile.ZipFile(source, 'r')
+				files = exportzip.namelist()
+				files.sort()
+
+				for file in files:
+					if not file.endswith('/'):
+						expfilename = str(generic_path.Join(destination, file))
+						exportwhatlog += "<member>" + escape(expfilename) + "</member>\n"
+
+				self.__Raptor.PrintXML("<clean bldinf='" + bldinf_filename + "' mmp='' config=''>\n")
+				self.__Raptor.PrintXML("<zipmarker>" + markerfilename + "</zipmarker>\n")
+				self.__Raptor.PrintXML("</clean>\n")
+
+				return exportwhatlog
+
+			exportzip = zipfile.ZipFile(source, 'r')
+			files = exportzip.namelist()
+			files.sort()
+			filecount = 0
+			for file in files:
+				expfilename = str(generic_path.Join(destination, file))
+				if file.endswith('/'):
+					try:
+						os.makedirs(expfilename)
+					except OSError, e:
+						pass # errors to do with "already exists" are not interesting.
+				else:
+					try:
+						os.makedirs(os.path.split(expfilename)[0])
+					except OSError, e:
+						pass # errors to do with "already exists" are not interesting.
+
+					try:
+						if os.path.exists(expfilename):
+							os.chmod(expfilename,stat.S_IREAD | stat.S_IWRITE)
+						expfile = open(expfilename, 'wb')
+						expfile.write(exportzip.read(file))
+						expfile.close()
+						
+						# Resurrect any file execution permissions present in the archived version
+						if (exportzip.getinfo(file).external_attr >> 16L) & 0100:
+							os.chmod(expfilename, stat.S_IMODE(os.stat(expfilename).st_mode) | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)						
+						
+						# Each file keeps its modified time the same as what it was before unzipping
+						accesstime = time.time()
+						datetime = exportzip.getinfo(file).date_time
+						timeTuple=(int(datetime[0]), int(datetime[1]), int(datetime[2]), int(datetime[3]), \
+									int(datetime[4]), int(datetime[5]), int(0), int(0), int(0))
+						modifiedtime = time.mktime(timeTuple)
+						os.utime(expfilename,(accesstime, modifiedtime))
+
+						filecount += 1
+						exportwhatlog+="<member>" + escape(expfilename) + "</member>\n"
+					except IOError, e:
+						message = "Could not unzip %s to %s: file %s: %s" %(source, destination, expfilename, str(e))
+						if not self.__Raptor.keepGoing:
+							raise MetaDataError(message)
+						else:
+							self.__Raptor.Error(message, bldinf=bldinf_filename)
+
+			markerfile = open(markerfilename, 'wb+')
+			markerfile.close()
+			self.__Raptor.PrintXML("<clean bldinf='" + bldinf_filename + "' mmp='' config=''>\n")
+			self.__Raptor.PrintXML("<zipmarker>" + markerfilename +	"</zipmarker>\n")
+			self.__Raptor.PrintXML("</clean>\n")
+
+		except IOError, e:
+			self.__Raptor.Warn("Problem while unzipping export %s to %s: %s",source,destination,str(e))
+
+		self.__Raptor.Info("Unzipped %d files from %s to %s", filecount, source, destination)
+		return exportwhatlog
+
+	def ProcessTEMs(self, componentNode, buildPlatform):
+		"""Add Template Extension Makefile nodes for a given platform
+		   to a skeleton bld.inf node.
+
+		This happens after exports have been handled.
+		"""
+		if buildPlatform["ISFEATUREVARIANT"]:
+			return	# feature variation does not run extensions at all
+		
+		if buildPlatform["TESTCODE"]:
+			extensions = componentNode.component.bldinf.getTestExtensions(buildPlatform)
+		else:
+			extensions = componentNode.component.bldinf.getExtensions(buildPlatform)
+
+		self.__Raptor.Debug("%i template extension makefiles for %s",
+							len(extensions), str(componentNode.component.bldinf.filename))
+
+		for i,extension in enumerate(extensions):
+			if self.__Raptor.projects:
+				if not extension.nametag in self.__Raptor.projects:
+					self.__Raptor.Debug("Skipping %s", extension.getMakefile())
+					continue
+				elif extension.nametag in self.projectList:
+					self.projectList.remove(extension.nametag)
+
+			extensionSpec = raptor_data.Specification("extension" + str(i))
+
+			interface = buildPlatform["extension"]
+			customInterface = False
+
+			# is there an FLM replacement for this extension?
+			if extension.interface:
+				try:
+					interface = self.__Raptor.cache.FindNamedInterface(extension.interface, buildPlatform["CACHEID"])
+					customInterface = True
+				except KeyError:
+					# no, there isn't an FLM
+					pass
+
+			extensionSpec.SetInterface(interface)
+
+			var = raptor_data.Variant()
+			var.AddOperation(raptor_data.Set("EPOCBLD", "$(OUTPUTPATH)"))
+			var.AddOperation(raptor_data.Set("PLATFORM", buildPlatform["PLATFORM"]))
+			var.AddOperation(raptor_data.Set("PLATFORM_PATH", buildPlatform["PLATFORM"].lower()))
+			var.AddOperation(raptor_data.Set("CFG", "$(VARIANTTYPE)"))
+			var.AddOperation(raptor_data.Set("CFG_PATH", "$(VARIANTTYPE)"))
+			var.AddOperation(raptor_data.Set("GENERATEDCPP", "$(OUTPUTPATH)"))
+			var.AddOperation(raptor_data.Set("TEMPLATE_EXTENSION_MAKEFILE", extension.getMakefile()))
+			var.AddOperation(raptor_data.Set("TEMCOUNT", str(i)))
+
+			# Extension inputs are added to the build spec.
+			# '$'s are escaped so that they are not expanded by Raptor or
+			# by Make in the call to the FLM
+			# The Extension makefiles are supposed to expand them themselves
+			# Path separators need not be parameterised anymore
+			# as bash is the standard shell
+			standardVariables = extension.getStandardVariables()
+			for standardVariable in standardVariables.keys():
+				self.__Raptor.Debug("Set %s=%s", standardVariable, standardVariables[standardVariable])
+				value = standardVariables[standardVariable].replace('$(', '$$$$(')
+				value = value.replace('$/', '/').replace('$;', ':')
+				var.AddOperation(raptor_data.Set(standardVariable, value))
+
+			# . . . as with the standard variables but the names and number
+			# of options are not known in advance so we add them to
+			# a "structure" that is self-describing
+			var.AddOperation(raptor_data.Set("O._MEMBERS", ""))
+			options = extension.getOptions()
+			for option in options:
+				self.__Raptor.Debug("Set %s=%s", option, options[option])
+				value = options[option].replace('$(EPOCROOT)', '$(EPOCROOT)/')
+				value = value.replace('$(', '$$$$(')
+				value = value.replace('$/', '/').replace('$;', ':')
+				value = value.replace('$/', '/').replace('$;', ':')
+
+				if customInterface:
+					var.AddOperation(raptor_data.Set(option, value))
+				else:
+					var.AddOperation(raptor_data.Append("O._MEMBERS", option))
+					var.AddOperation(raptor_data.Set("O." + option, value))
+
+			extensionSpec.AddVariant(var)
+			componentNode.AddChild(extensionSpec)
+
+
+	def ProcessMMPs(self, componentNode, buildPlatform):
+		"""Add project nodes for a given platform to a skeleton bld.inf node.
+
+		This happens after exports have been handled.
+		"""
+		gnuList = []
+		makefileList = []
+
+
+		component = componentNode.component
+
+
+		if buildPlatform["TESTCODE"]:
+			MMPList = component.bldinf.getTestMMPList(buildPlatform)
+		else:
+			MMPList = component.bldinf.getMMPList(buildPlatform)
+
+		bldInfFile = component.bldinf.filename
+
+		for mmpFileEntry in MMPList['mmpFileList']:
+			component.AddMMP(mmpFileEntry.filename) # Tell the component another mmp is specified (for this platform)
+
+			projectname = mmpFileEntry.filename.File().lower()
+
+			if self.__Raptor.projects:
+				if not projectname in self.__Raptor.projects:
+					self.__Raptor.Debug("Skipping %s", str(mmpFileEntry.filename))
+					continue
+				elif projectname in self.projectList:
+					self.projectList.remove(projectname)
+
+			foundmmpfile = (mmpFileEntry.filename).FindCaseless()
+
+			if foundmmpfile == None:
+				self.__Raptor.Error("Can't find mmp file '%s'", str(mmpFileEntry.filename), bldinf=str(bldInfFile))
+				continue
+
+			mmpFile = MMPFile(foundmmpfile,
+								   self.__gnucpp,
+								   component.bldinf,
+								   component.depfiles,
+								   log = self.__Raptor)
+
+			mmpFilename = mmpFile.filename
+
+			self.__Raptor.Info("Processing %s for platform %s",
+							   str(mmpFilename),
+							   " + ".join([x.name for x in buildPlatform["configs"]]))
+
+			# Run the Parser
+			# The backend supplies the actions
+			content = mmpFile.getContent(buildPlatform)
+			backend = MMPRaptorBackend(self.__Raptor, str(mmpFilename), str(bldInfFile))
+			parser  = MMPParser(backend)
+			parseresult = None
+			try:
+				parseresult = parser.mmp.parseString(content)
+			except ParseException,e:
+				self.__Raptor.Debug(e) # basically ignore parse exceptions
+
+			if (not parseresult) or (parseresult[0] != 'MMP'):
+				self.__Raptor.Error("The MMP Parser didn't recognise the mmp file '%s'",
+					                str(mmpFileEntry.filename), 
+					                bldinf=str(bldInfFile))
+				self.__Raptor.Debug(content)
+				self.__Raptor.Debug("The parse result was %s", parseresult)
+			else:
+				backend.finalise(buildPlatform)
+
+			# feature variation only processes FEATUREVARIANT binaries
+			if buildPlatform["ISFEATUREVARIANT"] and not backend.featureVariant:
+				continue
+			
+			# now build the specification tree
+			mmpSpec = raptor_data.Specification(generic_path.Path(getSpecName(mmpFilename)))
+			var = backend.BuildVariant
+
+			var.AddOperation(raptor_data.Set("PROJECT_META", str(mmpFilename)))
+
+			# If it is a TESTMMPFILE section, the FLM needs to know about it
+			if buildPlatform["TESTCODE"] and (mmpFileEntry.testoption in
+					["manual", "auto"]):
+
+				var.AddOperation(raptor_data.Set("TESTPATH",
+						mmpFileEntry.testoption.lower() + ".bat"))
+
+			# The output path for objects, stringtables and bitmaps specified by
+			# this MMP.  Adding in the requested target extension prevents build
+			# "fouling" in cases where there are several mmp targets which only differ
+			# by the requested extension. e.g. elocl.01 and elocl.18
+			var.AddOperation(raptor_data.Append("OUTPUTPATH","$(UNIQUETARGETPATH)",'/'))
+
+			# If the bld.inf entry for this MMP had the BUILD_AS_ARM option then
+			# tell the FLM.
+			if mmpFileEntry.armoption:
+				var.AddOperation(raptor_data.Set("ALWAYS_BUILD_AS_ARM","1"))
+
+			# what interface builds this node?
+			try:
+				interfaceName = buildPlatform[backend.getTargetType()]
+				mmpSpec.SetInterface(interfaceName)
+			except KeyError:
+				self.__Raptor.Error("Unsupported target type '%s' in %s",
+								    backend.getTargetType(),
+								    str(mmpFileEntry.filename),
+								    bldinf=str(bldInfFile))
+				continue
+
+			# Although not part of the MMP, some MMP-based build specs additionally require knowledge of their
+			# container bld.inf exported headers
+			for export in componentNode.component.bldinf.getExports(buildPlatform):
+				destination = export.getDestination()
+				if isinstance(destination, list):
+					exportfile = str(destination[0])
+				else:
+					exportfile = str(destination)
+
+				if re.search('\.h',exportfile,re.IGNORECASE):
+					var.AddOperation(raptor_data.Append("EXPORTHEADERS", str(exportfile)))
+
+			# now we have something worth adding to the component
+			mmpSpec.AddVariant(var)
+			componentNode.AddChild(mmpSpec)
+			
+			# if there are APPLY variants then add them to the mmpSpec too
+			for applyVar in backend.ApplyVariants:
+				try:
+					mmpSpec.AddVariant(self.__Raptor.cache.FindNamedVariant(applyVar))
+				except KeyError:
+					self.__Raptor.Error("APPLY unknown variant '%s' in %s",
+								        applyVar,
+								        str(mmpFileEntry.filename),
+								        bldinf=str(bldInfFile))
+
+			# resources, stringtables and bitmaps are sub-nodes of this project
+			# (do not add these for feature variant builds)
+			
+			if not buildPlatform["ISFEATUREVARIANT"]:
+				# Buildspec for Resource files
+				for i,rvar in enumerate(backend.ResourceVariants):
+					resourceSpec = raptor_data.Specification('resource' + str(i))
+					resourceSpec.SetInterface(buildPlatform['resource'])
+					resourceSpec.AddVariant(rvar)
+					mmpSpec.AddChild(resourceSpec)
+
+				# Buildspec for String Tables
+				for i,stvar in enumerate(backend.StringTableVariants):
+					stringTableSpec = raptor_data.Specification('stringtable' + str(i))
+					stringTableSpec.SetInterface(buildPlatform['stringtable'])
+					stringTableSpec.AddVariant(stvar)
+					mmpSpec.AddChild(stringTableSpec)
+
+				# Buildspec for Bitmaps
+				for i,bvar in enumerate(backend.BitmapVariants):
+					bitmapSpec = raptor_data.Specification('bitmap' + str(i))
+					bitmapSpec.SetInterface(buildPlatform['bitmap'])
+					bitmapSpec.AddVariant(bvar)
+					mmpSpec.AddChild(bitmapSpec)
+
+		# feature variation does not run extensions at all
+		# so return without considering .*MAKEFILE sections
+		if buildPlatform["ISFEATUREVARIANT"]:
+			return
+			
+		# Build spec for gnumakefile
+		for g in MMPList['gnuList']:
+			projectname = g.getMakefileName().lower()
+
+			if self.__Raptor.projects:
+				if not projectname in self.__Raptor.projects:
+					self.__Raptor.Debug("Skipping %s", str(g.getMakefileName()))
+					continue
+				elif projectname in self.projectList:
+					self.projectList.remove(projectname)
+
+			self.__Raptor.Debug("%i gnumakefile extension makefiles for %s",
+						len(gnuList), str(componentNode.component.bldinf.filename))
+			var = raptor_data.Variant()
+			gnuSpec = raptor_data.Specification("gnumakefile " + str(g.getMakefileName()))
+			interface = buildPlatform["ext_makefile"]
+			gnuSpec.SetInterface(interface)
+			gnumakefilePath = raptor_utilities.resolveSymbianPath(str(bldInfFile), g.getMakefileName())
+			var.AddOperation(raptor_data.Set("EPOCBLD", "$(OUTPUTPATH)"))
+			var.AddOperation(raptor_data.Set("PLATFORM", buildPlatform["PLATFORM"]))
+			var.AddOperation(raptor_data.Set("EXTMAKEFILENAME", g.getMakefileName()))
+			var.AddOperation(raptor_data.Set("DIRECTORY",g.getMakeDirectory()))
+			var.AddOperation(raptor_data.Set("CFG","$(VARIANTTYPE)"))
+			standardVariables = g.getStandardVariables()
+			for standardVariable in standardVariables.keys():
+				self.__Raptor.Debug("Set %s=%s", standardVariable, standardVariables[standardVariable])
+				value = standardVariables[standardVariable].replace('$(', '$$$$(')
+				value = value.replace('$/', '/').replace('$;', ':')
+				var.AddOperation(raptor_data.Set(standardVariable, value))
+			gnuSpec.AddVariant(var)
+			componentNode.AddChild(gnuSpec)
+
+		# Build spec for makefile
+		for m in MMPList['makefileList']:
+			projectname = m.getMakefileName().lower()
+
+			if self.__Raptor.projects:
+				if not projectname in self.__Raptor.projects:
+					self.__Raptor.Debug("Skipping %s", str(m.getMakefileName()))
+					continue
+				elif projectname in self.projectList:
+					self.projectList.remove(projectname)
+
+			self.__Raptor.Debug("%i makefile extension makefiles for %s",
+						len(makefileList), str(componentNode.component.bldinf.filename))
+			var = raptor_data.Variant()
+			gnuSpec = raptor_data.Specification("makefile " + str(m.getMakefileName()))
+			interface = buildPlatform["ext_makefile"]
+			gnuSpec.SetInterface(interface)
+			gnumakefilePath = raptor_utilities.resolveSymbianPath(str(bldInfFile), m.getMakefileName())
+			var.AddOperation(raptor_data.Set("EPOCBLD", "$(OUTPUTPATH)"))
+			var.AddOperation(raptor_data.Set("PLATFORM", buildPlatform["PLATFORM"]))
+			var.AddOperation(raptor_data.Set("EXTMAKEFILENAME", m.getMakefileName()))
+			var.AddOperation(raptor_data.Set("DIRECTORY",m.getMakeDirectory()))
+			var.AddOperation(raptor_data.Set("CFG","$(VARIANTTYPE)"))
+			var.AddOperation(raptor_data.Set("USENMAKE","1"))
+			standardVariables = m.getStandardVariables()
+			for standardVariable in standardVariables.keys():
+				self.__Raptor.Debug("Set %s=%s", standardVariable, standardVariables[standardVariable])
+				value = standardVariables[standardVariable].replace('$(', '$$$$(')
+				value = value.replace('$/', '/').replace('$;', ':')
+				var.AddOperation(raptor_data.Set(standardVariable, value))
+			gnuSpec.AddVariant(var)
+			componentNode.AddChild(gnuSpec)
+
+
+	def ApplyOSVariant(self, aBuildUnit, aEpocroot):
+		# Form path to kif.xml and path to buildinfo.txt
+		kifXmlPath = generic_path.Join(aEpocroot, "epoc32", "data","kif.xml")
+		buildInfoTxtPath = generic_path.Join(aEpocroot, "epoc32", "data","buildinfo.txt")
+
+		# Start with osVersion being None. This variable is a string and does two things:
+		# 1) is a representation of the OS version
+		# 2) is potentially the name of a variant
+		osVersion = None
+		if kifXmlPath.isFile(): # kif.xml exists so try to read it
+			osVersion = getOsVerFromKifXml(str(kifXmlPath))
+			if osVersion != None:
+				self.__Raptor.Info("OS version \"%s\" determined from file \"%s\"" % (osVersion, kifXmlPath))
+
+		# OS version was not determined from the kif.xml, e.g. because it doesn't exist
+		# or there was a problem parsing it. So, we fall over to using the buildinfo.txt
+		if osVersion == None and buildInfoTxtPath.isFile():
+			osVersion = getOsVerFromBuildInfoTxt(str(buildInfoTxtPath))
+			if osVersion != None:
+				self.__Raptor.Info("OS version \"%s\" determined from file \"%s\"" % (osVersion, buildInfoTxtPath))
+
+		# If we determined a non-empty string for the OS Version, attempt to apply it
+		if osVersion and osVersion in self.__Raptor.cache.variants:
+			self.__Raptor.Info("applying the OS variant to the configuration \"%s\"." % aBuildUnit.name)
+			aBuildUnit.variants.append(self.__Raptor.cache.variants[osVersion])
+		else:
+			self.__Raptor.Info("no OS variant for the configuration \"%s\"." % aBuildUnit.name)
+
--- a/sbsv2/raptor/python/raptor_start.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/raptor_start.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,42 +1,42 @@
-#
-# 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: 
-# lightweight script to start raptor
-#
-
-import raptor
-import sys
-import os
-
-profile_basename = None
-if os.environ.has_key('SBS_PROFILE_BASENAME'):
-	profile_basename = os.environ['SBS_PROFILE_BASENAME']
-	import cProfile
-
-#
-# Main takes the command-line (ignoring argv[0] which is the name of
-# this script) and returns the exit code.
-#
-try:	
-	if profile_basename is not None:
-		sys.exit(cProfile.run('raptor.Main(sys.argv[1:])',profile_basename))
-	else:
-		sys.exit(raptor.Main(sys.argv[1:]))
-except KeyboardInterrupt:
-	sys.stderr.write("ERROR: sbs: Terminated by control-c or break\n")
-	sys.exit(255)
-except ValueError, exc:
-	sys.stderr.write("ERROR: sbs: %s" % str(exc))
-	sys.exit(255)
-
+#
+# 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: 
+# lightweight script to start raptor
+#
+
+import raptor
+import sys
+import os
+
+profile_basename = None
+if os.environ.has_key('SBS_PROFILE_BASENAME'):
+	profile_basename = os.environ['SBS_PROFILE_BASENAME']
+	import cProfile
+
+#
+# Main takes the command-line (ignoring argv[0] which is the name of
+# this script) and returns the exit code.
+#
+try:	
+	if profile_basename is not None:
+		sys.exit(cProfile.run('raptor.Main(sys.argv[1:])',profile_basename))
+	else:
+		sys.exit(raptor.Main(sys.argv[1:]))
+except KeyboardInterrupt:
+	sys.stderr.write("ERROR: sbs: Terminated by control-c or break\n")
+	sys.exit(255)
+except ValueError, exc:
+	sys.stderr.write("ERROR: sbs: %s" % str(exc))
+	sys.exit(255)
+
--- a/sbsv2/raptor/python/raptor_utilities.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/raptor_utilities.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,191 +1,240 @@
-#
-# 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: 
-# raptor_utilities module
-# Useful wrapper functions and classes used in Raptor processing
-#
-
-import generic_path
-import os.path
-import re
-import sys
-
-dosSlashRegEx = re.compile(r'\\')
-unixSlashRegEx = re.compile(r'/')
-dosDriveRegEx = re.compile("^([A-Za-z]{1}):")
-
-def getOSPlatform():
-	return sys.platform.lower()
-
-def getOSFileSystem():
-	if getOSPlatform().startswith("win"):
-		return "cygwin"
-	else:
-		return "unix"
-
-def convertToUnixSlash(aReference):
-	return dosSlashRegEx.sub(r'/', aReference)
-
-def convertToDOSSlash(aReference):
-	return unixSlashRegEx.sub(r'\\', aReference)
-
-def absPathFromPath(aPathRoot, aReference):
-	pathRoot = convertToUnixSlash(aPathRoot)
-	reference = convertToUnixSlash(aReference)
-	
-	if os.path.isabs(reference):
-		reference = reference.lstrip(r'/')
-	
-	joined = os.path.join(pathRoot, reference)
-	
-	return os.path.abspath(joined)
-   
-
-def absPathFromFile(aFileRoot, aReference):
-	pathRoot = os.path.dirname(aFileRoot)
-	return absPathFromPath(pathRoot, aReference)
-
-def sanitise(aPotentialFilename):
-	"Take a string and return a version suitable for use as a filename."
-	return re.sub("(\\\\|\/|:|;| )", "_", aPotentialFilename)
-
-def resolveSymbianPath(aFileRoot, aReference, aMainType="", aSubType="", aEPOCROOT="$(EPOCROOT)"):
-	""" Convert raw Symbian metadata path/file references into absolute makefile references, or list of references
-
-	<drive>-prefix	: maps to an emulated drive depending on the following cases:
-							(a) If the drive is C:, it maps to the *two* locations
-								$(EPOCROOT)/epoc32/data/<drive>/<path> and
-								$(EPOCROOT)/epoc32/winscw/<drive>/<path>
-							(b) If the drive is A:, B:, or D: to Z:, it maps to the *three* locations
-								$(EPOCROOT)/epoc32/data/<drive>/<path> and
-								$(EPOCROOT)/epoc32/release/winscw/udeb/<drive>/<path> and
-								$(EPOCROOT)/epoc32/release/winscw/urel/<drive>/<path>
-	Absolute 		: true absolute if:
-							(a) PRJ_*EXPORTS destination or DEFFILE location and
-							(b) not starting with an 'epoc32'
-						otherwise relative to $(EPOCROOT)
-	Relative 		: relative to $(EPOCROOT)/epoc32/include if:
-							(a) PRJ_EXPORTS destination and
-							(b) not a :zip statement,
-					  relative to $(EPOCROOT) if:
-							(a) PRJ_(TEST)EXPORTS destination and
-							(b) a :zip statement,
-						otherwise relative to aFileRoot
-	|-prefix 		: relative to aFileRoot
-	+-prefix 		: relative to $(EPOCROOT)/epoc32"""
-	
-	# Both reference and fileroot can have backslashes - so convert them.
-	reference = convertToUnixSlash(aReference)
-	fileroot = convertToUnixSlash(aFileRoot)
-	
-	# Remove Trailing backslashes so that the expansions doesnt mess up the shell
-	if reference.endswith('/') and len(reference) > 1:
-		reference = reference.rstrip('/')
-
-	emulatedDrive = dosDriveRegEx.match(reference)	
-	if emulatedDrive:
-		# Emulated drive C:/ Z:/ and the like
-		# C: drive 
-		if reference.lower().startswith("c"):
-			resolvedPath = []
-			resolvedPath.append(dosDriveRegEx.sub(aEPOCROOT+'/epoc32/data/'+emulatedDrive.group(1), reference))
-			resolvedPath.append(dosDriveRegEx.sub(aEPOCROOT+'/epoc32/winscw/'+emulatedDrive.group(1), reference))
-		else: # Other letters: A, B and D to Z
-			resolvedPath = []
-			resolvedPath.append(dosDriveRegEx.sub(aEPOCROOT+'/epoc32/data/'+emulatedDrive.group(1), reference))
-			resolvedPath.append(dosDriveRegEx.sub(aEPOCROOT+'/epoc32/release/winscw/udeb/'+emulatedDrive.group(1), reference))
-			resolvedPath.append(dosDriveRegEx.sub(aEPOCROOT+'/epoc32/release/winscw/urel/'+emulatedDrive.group(1), reference))
-	elif os.path.isabs(reference):
-		# Absolute
-		if re.search("(DEFFILE|PRJ_(TEST)?EXPORTS)", aMainType, re.I) and not re.search("^\/epoc32\/", reference, re.I):
-			# Ensures prepending of drive if on Windows
-			resolvedPath = os.path.abspath(reference)
-		else:
-			resolvedPath = aEPOCROOT + reference
-		
-	elif reference.startswith("+"):
-		# '+' prefix
-		reference = reference.lstrip(r'+')
-		resolvedPath = aEPOCROOT + '/epoc32'+reference
-	elif reference.startswith("|"):
-		# '|' prefix
-		reference = reference.lstrip(r'|')
-		resolvedPath = absPathFromFile(fileroot, reference)
-	else:
-		# Relative
-		if aMainType == "PRJ_EXPORTS" and aSubType != ":zip":
-			resolvedPath = aEPOCROOT + '/epoc32/include/'+reference
-		elif aSubType == ":zip":
-			resolvedPath = aEPOCROOT + '/' + reference
-		else:
-			resolvedPath = absPathFromFile(fileroot, aReference)
-	
-	if isinstance(resolvedPath, list):
-		# In this case, this is a list of export destinations, 
-		makefilePath = map(lambda x: str(generic_path.Path(x)), resolvedPath)
-	else:
-		makefilePath = str(generic_path.Path(resolvedPath))
-	
-	return makefilePath # Note this is either a list of strings, or a single string
-
-
-class ExternalTool(object):
-	""" Generic wrapper for an external tool
-	
-	Provides the basic means to wrap up a tool that is external to Raptor with a
-	consistent interface for both invocation and the capture of output."""
-	
-	def __init__(self, aTool):
-		self.__Tool = aTool
-		self.__Output = []
-
-	def call(self, aArgs):		
-		print "RUNNNING: %s %s" %(self.__Tool, aArgs)
-		(input, output) = os.popen2(self.__Tool + " " + aArgs)
-		self.__Output = output.read()
-		return output.close() 
-	
-	def getTool(self):
-		return self.__Tool
-
-	def getOutput(self):
-		return self.__Output
-		
-	def getOutputLines(self):
-		return self.__Output.split("\n")
-
-
-class NullLog(object):
-	""" If your class has these methods then it can act as a log """
-	def Info(self, format, *extras):
-		"Send an information message to the configured channel"
-		return
-
-	def ClockInfo(self):
-		"Print a timestamp in seconds"
-		return
-
-	def Debug(self, format, *extras):
-		"Send a debugging message to the configured channel"
-		return
-
-	def Warn(self, format, *extras):
-		"Send a warning message to the configured channel"
-		return
-
-	def Error(self, format, *extras):
-		"Send an error message to the configured channel"
-		return
-
-nulllog = NullLog()
+#
+# 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: 
+# raptor_utilities module
+# Useful wrapper functions and classes used in Raptor processing
+#
+
+import generic_path
+import os.path
+import re
+import sys
+import stat
+import shutil
+
+dosSlashRegEx = re.compile(r'\\')
+unixSlashRegEx = re.compile(r'/')
+dosDriveRegEx = re.compile("^([A-Za-z]{1}):")
+
+def getOSPlatform():
+	return sys.platform.lower()
+
+def getOSFileSystem():
+	if getOSPlatform().startswith("win"):
+		return "cygwin"
+	else:
+		return "unix"
+
+def convertToUnixSlash(aReference):
+	return dosSlashRegEx.sub(r'/', aReference)
+
+def convertToDOSSlash(aReference):
+	return unixSlashRegEx.sub(r'\\', aReference)
+
+def absPathFromPath(aPathRoot, aReference):
+	pathRoot = convertToUnixSlash(aPathRoot)
+	reference = convertToUnixSlash(aReference)
+	
+	if os.path.isabs(reference):
+		reference = reference.lstrip(r'/')
+	
+	joined = os.path.join(pathRoot, reference)
+	
+	return os.path.abspath(joined)
+   
+
+def absPathFromFile(aFileRoot, aReference):
+	pathRoot = os.path.dirname(aFileRoot)
+	return absPathFromPath(pathRoot, aReference)
+
+def sanitise(aPotentialFilename):
+	"Take a string and return a version suitable for use as a filename."
+	return re.sub("(\\\\|\/|:|;| )", "_", aPotentialFilename)
+
+def resolveSymbianPath(aFileRoot, aReference, aMainType="", aSubType="", aEPOCROOT="$(EPOCROOT)"):
+	""" Convert raw Symbian metadata path/file references into absolute makefile references, or list of references
+
+	<drive>-prefix	: maps to an emulated drive depending on the following cases:
+							(a) If the drive is C:, it maps to the *two* locations
+								$(EPOCROOT)/epoc32/data/<drive>/<path> and
+								$(EPOCROOT)/epoc32/winscw/<drive>/<path>
+							(b) If the drive is A:, B:, or D: to Z:, it maps to the *three* locations
+								$(EPOCROOT)/epoc32/data/<drive>/<path> and
+								$(EPOCROOT)/epoc32/release/winscw/udeb/<drive>/<path> and
+								$(EPOCROOT)/epoc32/release/winscw/urel/<drive>/<path>
+	Absolute 		: true absolute if:
+							(a) PRJ_*EXPORTS destination or DEFFILE location and
+							(b) not starting with an 'epoc32'
+						otherwise relative to $(EPOCROOT)
+	Relative 		: relative to $(EPOCROOT)/epoc32/include if:
+							(a) PRJ_EXPORTS destination and
+							(b) not a :zip statement,
+					  relative to $(EPOCROOT) if:
+							(a) PRJ_(TEST)EXPORTS destination and
+							(b) a :zip statement,
+						otherwise relative to aFileRoot
+	|-prefix 		: relative to aFileRoot
+	+-prefix 		: relative to $(EPOCROOT)/epoc32"""
+	
+	# Both reference and fileroot can have backslashes - so convert them.
+	reference = convertToUnixSlash(aReference)
+	fileroot = convertToUnixSlash(aFileRoot)
+	
+	# Remove Trailing backslashes so that the expansions doesnt mess up the shell
+	if reference.endswith('/') and len(reference) > 1:
+		reference = reference.rstrip('/')
+
+	emulatedDrive = dosDriveRegEx.match(reference)	
+	if emulatedDrive:
+		# Emulated drive C:/ Z:/ and the like
+		# C: drive 
+		if reference.lower().startswith("c"):
+			resolvedPath = []
+			resolvedPath.append(dosDriveRegEx.sub(aEPOCROOT+'/epoc32/data/'+emulatedDrive.group(1), reference))
+			resolvedPath.append(dosDriveRegEx.sub(aEPOCROOT+'/epoc32/winscw/'+emulatedDrive.group(1), reference))
+		else: # Other letters: A, B and D to Z
+			resolvedPath = []
+			resolvedPath.append(dosDriveRegEx.sub(aEPOCROOT+'/epoc32/data/'+emulatedDrive.group(1), reference))
+			resolvedPath.append(dosDriveRegEx.sub(aEPOCROOT+'/epoc32/release/winscw/udeb/'+emulatedDrive.group(1), reference))
+			resolvedPath.append(dosDriveRegEx.sub(aEPOCROOT+'/epoc32/release/winscw/urel/'+emulatedDrive.group(1), reference))
+	elif os.path.isabs(reference):
+		# Absolute
+		if re.search("(DEFFILE|PRJ_(TEST)?EXPORTS)", aMainType, re.I) and not re.search("^\/epoc32\/", reference, re.I):
+			# Ensures prepending of drive if on Windows
+			resolvedPath = os.path.abspath(reference)
+		else:
+			resolvedPath = aEPOCROOT + reference
+		
+	elif reference.startswith("+"):
+		# '+' prefix
+		reference = reference.lstrip(r'+')
+		resolvedPath = aEPOCROOT + '/epoc32'+reference
+	elif reference.startswith("|"):
+		# '|' prefix
+		reference = reference.lstrip(r'|')
+		resolvedPath = absPathFromFile(fileroot, reference)
+	else:
+		# Relative
+		if aMainType == "PRJ_EXPORTS" and aSubType != ":zip":
+			resolvedPath = aEPOCROOT + '/epoc32/include/'+reference
+		elif aSubType == ":zip":
+			resolvedPath = aEPOCROOT + '/' + reference
+		else:
+			resolvedPath = absPathFromFile(fileroot, aReference)
+	
+	if isinstance(resolvedPath, list):
+		# In this case, this is a list of export destinations, 
+		makefilePath = map(lambda x: str(generic_path.Path(x)), resolvedPath)
+	else:
+		makefilePath = str(generic_path.Path(resolvedPath))
+	
+	return makefilePath # Note this is either a list of strings, or a single string
+
+
+class ExternalTool(object):
+	""" Generic wrapper for an external tool
+	
+	Provides the basic means to wrap up a tool that is external to Raptor with a
+	consistent interface for both invocation and the capture of output."""
+	
+	def __init__(self, aTool):
+		self.__Tool = aTool
+		self.__Output = []
+
+	def call(self, aArgs):		
+		print "RUNNNING: %s %s" %(self.__Tool, aArgs)
+		(input, output) = os.popen2(self.__Tool + " " + aArgs)
+		self.__Output = output.read()
+		return output.close() 
+	
+	def getTool(self):
+		return self.__Tool
+
+	def getOutput(self):
+		return self.__Output
+		
+	def getOutputLines(self):
+		return self.__Output.split("\n")
+
+
+class NullLog(object):
+	""" If your class has these methods then it can act as a log """
+	def Info(self, format, *extras):
+		"Send an information message to the configured channel"
+		return
+
+	def ClockInfo(self):
+		"Print a timestamp in seconds"
+		return
+
+	def Debug(self, format, *extras):
+		"Send a debugging message to the configured channel"
+		return
+
+	def Warn(self, format, *extras):
+		"Send a warning message to the configured channel"
+		return
+
+	def Error(self, format, *extras):
+		"Send an error message to the configured channel"
+		return
+
+nulllog = NullLog()
+
+def copyfile(_source, _destination):
+	"""Copy the source file to the destination file (create a directory
+	   to copy into if it does not exist). Don't copy if the destination
+	   file exists and has an equal or newer modification time."""
+	source = generic_path.Path(str(_source).replace('%20',' '))
+	destination = generic_path.Path(str(_destination).replace('%20',' '))
+	dest_str = str(destination)
+	source_str = str(source)
+
+	try:
+
+
+		destDir = destination.Dir()
+		if not destDir.isDir():
+			os.makedirs(str(destDir))
+			shutil.copyfile(source_str, dest_str)
+			return 
+		# Destination file exists so we have to think about updating it
+		sourceMTime = 0
+		destMTime = 0
+		sourceStat = 0
+		try:
+			sourceStat = os.stat(source_str)
+			sourceMTime = sourceStat[stat.ST_MTIME]
+		except OSError, e:
+			message = "Source of copyfile does not exist:  " + str(source)
+			raise IOError(message)
+		try:
+			destMTime = os.stat(dest_str)[stat.ST_MTIME]
+		except OSError, e:
+			pass # destination doesn't have to exist
+
+		if destMTime == 0 or destMTime < sourceMTime:
+			if os.path.exists(dest_str):
+				os.chmod(dest_str,stat.S_IREAD | stat.S_IWRITE)
+			shutil.copyfile(source_str, dest_str)
+
+			# Ensure that the destination file remains executable if the source was also:
+			os.chmod(dest_str,sourceStat[stat.ST_MODE] | stat.S_IREAD | stat.S_IWRITE | stat.S_IWGRP ) 
+
+
+	except Exception,e:
+		message = "Could not update " + dest_str + " from " + source_str + " : " + str(e)
+		raise IOError(message)
+
+	return 
--- a/sbsv2/raptor/python/raptor_version.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/raptor_version.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,20 +1,27 @@
-#
-# 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: 
-# raptor version information module
-#
-
-def Version():
-	"""Raptor version string"""
-	return "2.10.1 [2009-10-27 sf prerelease]"
+#
+# 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: 
+# raptor version information module
+
+# replace CHANGESET with the Hg changeset for ANY release
+
+version=(2,14,0,"2010-05-19","symbian build system","CHANGESET")
+
+def numericversion():
+	"""Raptor version string"""
+	return "%d.%d.%d" % version[:3]
+
+def fullversion():
+	"""Raptor version string"""
+	return "%d.%d.%d [%s %s %s]" % version
--- a/sbsv2/raptor/python/raptor_xml.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/python/raptor_xml.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,363 +1,413 @@
-#
-# 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: 
-# raptor_xml module
-#
-
-import os
-import raptor_data
-import raptor_utilities
-import xml.dom.minidom
-import re
-import generic_path
-
-# raptor_xml module attributes
-
-namespace = "http://symbian.com/xml/build"
-xsdVersion = "build/2_0.xsd"
-xsdIgnore = "build/666.xsd"
-
-_constructors = {"alias":raptor_data.Alias,
-				 "aliasRef":raptor_data.AliasRef,
-				 "append":raptor_data.Append,
-				 "env":raptor_data.Env,
-				 "group":raptor_data.Group,
-				 "groupRef":raptor_data.GroupRef,
-				 "interface":raptor_data.Interface,
-				 "interfaceRef":raptor_data.InterfaceRef,
-				 "param":raptor_data.Parameter,
-				 "paramgroup":raptor_data.ParameterGroup,
-				 "prepend":raptor_data.Prepend,
-				 "set":raptor_data.Set,
-				 "spec":raptor_data.Specification,
-				 "var":raptor_data.Variant,
-				 "varRef":raptor_data.VariantRef}
-
-
-# raptor_xml module classes
-
-class XMLError(Exception):
-	pass
-
-# raptor_xml module functions
-
-def Read(Raptor, filename):
-	"Read in a Raptor XML document"
-
-	# try to read and parse the XML file
-	try:
-		dom = xml.dom.minidom.parse(filename)
-
-	except: # a whole bag of exceptions can be raised here
-		raise XMLError
-
-	# <build> is always the root element
-	build = dom.documentElement
-	objects = []
-
-	fileVersion = build.getAttribute("xsi:schemaLocation")
-	
-	# ignore the file it matches the "invalid" schema
-	if fileVersion.endswith(xsdIgnore):
-		return objects
-		
-	# check that the file matches the expected schema
-	if not fileVersion.endswith(xsdVersion):
-		Raptor.Warn("file '%s' uses schema '%s' which does not end with the expected version '%s'", filename, fileVersion, xsdVersion)
-		
-	# create a Data Model object from each sub-element
-	for child in build.childNodes:
-		if child.namespaceURI == namespace \
-		and child.nodeType == child.ELEMENT_NODE:
-			try:
-				o = XMLtoDataModel(Raptor, child)
-				if o is not None:
-					objects.append(o)
-			except raptor_data.InvalidChildError:
-				Raptor.Warn("Invalid element %s in %s", child.localName, filename)
-
-	# discard the XML
-	dom.unlink()
-	return objects
-
-
-def XMLtoDataModel(Raptor, node):
-	"Create a data-model object from an XML element"
-
-	# look-up a function to create an object from the node name
-	try:
-		constructor = _constructors[node.localName]
-
-	except KeyError:
-		Raptor.Warn("Unknown element %s", node.localName)
-		return
-
-	model = constructor()
-
-	# deal with the attributes first
-	if node.hasAttributes():
-		for i in range(node.attributes.length):
-			attribute = node.attributes.item(i)
-			try:
-
-				model.SetProperty(attribute.localName, attribute.value)
-
-			except raptor_data.InvalidPropertyError:
-				Raptor.Warn("Can't set attribute %s for element %s",
-							 attribute.localName, node.localName)
-
-	# add the sub-elements
-	for child in node.childNodes:
-		if child.namespaceURI == namespace \
-		and child.nodeType == child.ELEMENT_NODE:
-			try:
-				gc = XMLtoDataModel(Raptor, child)
-				if gc is not None:
-					model.AddChild(gc)
-
-			except raptor_data.InvalidChildError:
-				Raptor.Warn("Can't add child %s to element %s",
-							 child.localName, node.localName)
-
-	# only return a valid object (or raise error)
-	if model.Valid():
-		if model.IsApplicable():
-			return model
-		else:
-			return None
-	else:
-		raise raptor_data.InvalidChildError
-
-
-class SystemModelComponent(generic_path.Path):
-	"""Path sub-class that wraps up a component bld.inf file with
-	system_definition.xml context information."""
-
-	def __init__(self, aBldInfFile, aContainerNames, aSystemDefinitionFile, aSystemDefinitionBase, aSystemDefinitionVersion):
-		generic_path.Path.__init__(self, aBldInfFile.Absolute().path)
-		self.__ContainerNames = aContainerNames
-		self.__SystemDefinitionFile = aSystemDefinitionFile
-		self.__SystemDefinitionBase = aSystemDefinitionBase
-		self.__SystemDefinitionVersion = aSystemDefinitionVersion
-
-	def GetSystemDefinitionFile(self):
-		return self.__SystemDefinitionFile
-
-	def GetSystemDefinitionBase(self):
-		return self.__SystemDefinitionBase
-
-	def GetSystemDefinitionFile(self):
-		return self.__SystemDefinitionVersion
-
-	def GetContainerName(self, aContainerType):
-		if self.__ContainerNames.has_key(aContainerType):
-		  return self.__ContainerNames[aContainerType]
-		return ""
-
-
-class SystemModel(object):
-	"""A representation of the SystemModel section of a Symbian system_definition.xml file."""
-
-	def __init__(self, aLogger, aSystemDefinitionFile, aSystemDefinitionBase):
-		self.__Logger = aLogger
-		self.__SystemDefinitionFile = aSystemDefinitionFile.GetLocalString()
-		self.__SystemDefinitionBase = aSystemDefinitionBase.GetLocalString()
-		self.__Version = {'MAJOR':0,'MID':0,'MINOR':0}
-		self.__ComponentRoot = ""
-		self.__TotalComponents = 0
-		self.__LayerList = []
-		self.__LayerDetails = {}
-
-		self.__DOM = None
-		self.__SystemDefinitionElement = None
-
-		if self.__Read():
-			if self.__Validate():
-				self.__Parse()
-
-		if self.__DOM:
-			self.__DOM.unlink()
-
-	def HasLayer(self, aLayer):
-		return aLayer in self.__LayerList
-
-	def GetLayerNames(self):
-		return self.__LayerList
-
-	def GetLayerComponents(self, aLayer):
-		if not self.HasLayer(aLayer):
-			self.__Logger.Error("System Definition layer \"%s\" does not exist in %s", aLayer, self.__SystemDefinitionFile)
-			return []
-
-		return self.__LayerDetails[aLayer]
-
-	def IsLayerBuildable(self, aLayer):
-		if len(self.GetLayerComponents(aLayer)):
-			return True
-		return False
-
-	def GetAllComponents(self):
-		components = []
-
-		for layer in self.GetLayerNames():
-			components.extend(self.GetLayerComponents(layer))
-
-		return components
-
-	def DumpLayerInfo(self, aLayer):
-		if self.HasLayer(aLayer):
-			self.__Logger.Info("Found %d bld.inf references in layer \"%s\"", len(self.GetLayerComponents(aLayer)), aLayer)
-
-	def DumpInfo(self):
-		self.__Logger.Info("Found %d bld.inf references in %s within %d layers:", len(self.GetAllComponents()), self.__SystemDefinitionFile, len(self.GetLayerNames()))
-		self.__Logger.Info("\t%s", ", ".join(self.GetLayerNames()))
-
-	def __Read(self):
-		if not os.path.exists(self.__SystemDefinitionFile):
-			self.__Logger.Error("System Definition file %s does not exist", self.__SystemDefinitionFile)
-			return False
-
-		self.__Logger.Info("System Definition file %s", self.__SystemDefinitionFile)
-
-		# try to read the XML file
-		try:
-			self.__DOM = xml.dom.minidom.parse(self.__SystemDefinitionFile)
-
-		except: # a whole bag of exceptions can be raised here
-			self.__Logger.Error("Failed to parse XML file %s", self.__SystemDefinitionFile)
-			return False
-
-		# <SystemDefinition> is always the root element
-		self.__SystemDefinitionElement = self.__DOM.documentElement
-
-		return True
-
-	def __Validate(self):
-		# account for different schema versions in processing
-		# old format : version >= 1.3.0
-		# new format : version >= 2.0.0 (assume later versions are compatible...at least for now)
-		version = re.match(r'(?P<MAJOR>\d)\.(?P<MID>\d)(\.(?P<MINOR>\d))?', self.__SystemDefinitionElement.getAttribute("schema"))
-
-		if not version:
-			self.__Logger.Error("Cannot determine schema version of XML file %s", self.__SystemDefinitionFile)
-			return False
-
-		self.__Version['MAJOR'] = int(version.group('MAJOR'))
-		self.__Version['MID'] = int(version.group('MID'))
-		self.__Version['MINOR'] = int(version.group('MINOR'))
-
-		if self.__Version['MAJOR'] == 1 and self.__Version['MID'] > 2:
-			self.__ComponentRoot = self.__SystemDefinitionBase
-		elif self.__Version['MAJOR'] == 2:
-			# 2.0.0 format supports SOURCEROOT as an environment specified base - we respect this, unless
-			# explicitly overridden on the command line
-			if os.environ.has_key('SOURCEROOT'):
-				self.__ComponentRoot = generic_path.Path(os.environ['SOURCEROOT'])
-			if self.__SystemDefinitionBase and self.__SystemDefinitionBase != ".":
-				self.__ComponentRoot = self.__SystemDefinitionBase
-				if os.environ.has_key('SOURCEROOT'):
-					self.__Logger.Info("Command line specified System Definition file base \'%s\' overriding environment SOURCEROOT \'%s\'", self.__SystemDefinitionBase, os.environ['SOURCEROOT'])
-		else:
-			self.__Logger.Error("Cannot process schema version %s of file %s", version.string, self.__SystemDefinitionFile)
-			return False
-
-		return True
-
-	def __Parse(self):
-		# find the <systemModel> element (there can be 0 or 1) and search any <layer> elements for <unit> elements with "bldFile" attributes
-		# the <layer> context of captured "bldFile" attributes is recorded as we go
-		for child in self.__SystemDefinitionElement.childNodes:
-			if child.localName == "systemModel":
-				self.__ProcessSystemModelElement(child)
-
-	def __CreateComponent(self, aBldInfFile, aUnitElement):
-		# take a resolved bld.inf file and associated <unit/> element and returns a populated Component object
-		containers = {}
-		self.__GetElementContainers(aUnitElement, containers)
-		component = SystemModelComponent(aBldInfFile, containers, self.__SystemDefinitionFile, self.__SystemDefinitionBase, self.__Version)
-
-		return component
-
-	def __GetElementContainers(self, aElement, aContainers):
-		# take a <unit/> element and creates a type->name dictionary of all of its parent containers
-		# We're only interested in parent nodes if they're not the top-most node
-		if aElement.parentNode.parentNode:
-			parent = aElement.parentNode
-			name = parent.getAttribute("name")
-
-			if name:
-				aContainers[parent.tagName] = name
-
-			self.__GetElementContainers(parent, aContainers)
-
-	def __ProcessSystemModelElement(self, aElement):
-		"""Search for XML <unit/> elements with 'bldFile' attributes and resolve concrete bld.inf locations
-		with an appreciation of different schema versions."""
-
-		if aElement.tagName == "layer":
-			currentLayer = aElement.getAttribute("name")
-
-			if not self.__LayerDetails.has_key(currentLayer):
-				self.__LayerDetails[currentLayer] = []
-
-			if not currentLayer in self.__LayerList:
-				self.__LayerList.append(currentLayer)
-
-		elif aElement.tagName == "unit" and aElement.hasAttributes():
-			bldFileValue = aElement.getAttribute("bldFile")
-
-			if bldFileValue:
-				bldInfRoot = self.__ComponentRoot
-
-				if self.__Version['MAJOR'] == 1 and self.__Version['MID'] == 4:
-					# version 1.4.x schema paths can use DOS slashes
-					bldFileValue = raptor_utilities.convertToUnixSlash(bldFileValue)
-				elif self.__Version['MAJOR'] == 2:
-					# version 2.x.x schema paths are subject to a "root" attribute off-set, if it exists
-					rootValue = aElement.getAttribute("root")
-
-					if rootValue:
-						if os.environ.has_key(rootValue):
-							bldInfRoot = generic_path.Path(os.environ[rootValue])
-						else:
-							# Assume that this is an error i.e. don't attempt to resolve in relation to SOURCEROOT
-							bldInfRoot = None
-							self.__Logger.Error("Cannot resolve \'root\' attribute value \"%s\" in %s", rootValue, self.__SystemDefinitionFile)
-							return
-
-				group = generic_path.Path(bldFileValue)
-
-				if not group.isAbsolute() and bldInfRoot:
-					group = generic_path.Join(bldInfRoot, group)
-
-				bldinf = generic_path.Join(group, "bld.inf").FindCaseless()
-
-				if bldinf == None:
-					self.__Logger.Error("No bld.inf found at %s in %s", group.GetLocalString(), self.__SystemDefinitionFile)
-				else:
-					component = self.__CreateComponent(bldinf, aElement)
-					layer = component.GetContainerName("layer")
-					if layer:
-						self.__LayerDetails[layer].append(component)
-						self.__TotalComponents += 1
-					else:
-						self.__Logger.Error("No containing layer found for %s in %s", str(bldinf), self.__SystemDefinitionFile)
-
-		# search the sub-elements
-		for child in aElement.childNodes:
-			if child.nodeType == child.ELEMENT_NODE:
-				self.__ProcessSystemModelElement(child)
-
-
-# end of the raptor_xml module
+#
+# 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:
+# raptor_xml module
+#
+
+import os
+import raptor_data
+import raptor_utilities
+import xml.dom.minidom
+import re
+import generic_path
+
+# raptor_xml module attributes
+
+namespace = "http://symbian.com/xml/build"
+xsdVersion = "build/2_0.xsd"
+xsdIgnore = "build/666.xsd"
+
+_constructors = {"alias":raptor_data.Alias,
+				 "aliasRef":raptor_data.AliasRef,
+				 "append":raptor_data.Append,
+				 "env":raptor_data.Env,
+				 "group":raptor_data.Group,
+				 "groupRef":raptor_data.GroupRef,
+				 "interface":raptor_data.Interface,
+				 "interfaceRef":raptor_data.InterfaceRef,
+				 "param":raptor_data.Parameter,
+				 "paramgroup":raptor_data.ParameterGroup,
+				 "prepend":raptor_data.Prepend,
+				 "set":raptor_data.Set,
+				 "spec":raptor_data.Specification,
+				 "var":raptor_data.Variant,
+				 "varRef":raptor_data.VariantRef}
+
+
+# raptor_xml module classes
+
+class XMLError(Exception):
+	pass
+
+# raptor_xml module functions
+
+def Read(Raptor, filename):
+	"Read in a Raptor XML document"
+
+	# try to read and parse the XML file
+	try:
+		dom = xml.dom.minidom.parse(filename)
+
+	except: # a whole bag of exceptions can be raised here
+		raise XMLError
+
+	# <build> is always the root element
+	build = dom.documentElement
+	objects = []
+
+	fileVersion = build.getAttribute("xsi:schemaLocation")
+
+	# ignore the file it matches the "invalid" schema
+	if fileVersion.endswith(xsdIgnore):
+		return objects
+
+	# check that the file matches the expected schema
+	if not fileVersion.endswith(xsdVersion):
+		Raptor.Warn("file '%s' uses schema '%s' which does not end with the expected version '%s'", filename, fileVersion, xsdVersion)
+
+	# create a Data Model object from each sub-element
+	for child in build.childNodes:
+		if child.namespaceURI == namespace \
+		and child.nodeType == child.ELEMENT_NODE:
+			try:
+				o = XMLtoDataModel(Raptor, child)
+				if o is not None:
+					objects.append(o)
+			except raptor_data.InvalidChildError:
+				Raptor.Warn("Invalid element %s in %s", child.localName, filename)
+
+	# discard the XML
+	dom.unlink()
+	return objects
+
+
+def XMLtoDataModel(Raptor, node):
+	"Create a data-model object from an XML element"
+
+	# look-up a function to create an object from the node name
+	try:
+		constructor = _constructors[node.localName]
+
+	except KeyError:
+		Raptor.Warn("Unknown element %s", node.localName)
+		return
+
+	model = constructor()
+
+	# deal with the attributes first
+	if node.hasAttributes():
+		for i in range(node.attributes.length):
+			attribute = node.attributes.item(i)
+			try:
+
+				model.SetProperty(attribute.localName, attribute.value)
+
+			except raptor_data.InvalidPropertyError:
+				Raptor.Warn("Can't set attribute %s for element %s",
+							 attribute.localName, node.localName)
+
+	# add the sub-elements
+	for child in node.childNodes:
+		if child.namespaceURI == namespace \
+		and child.nodeType == child.ELEMENT_NODE:
+			try:
+				gc = XMLtoDataModel(Raptor, child)
+				if gc is not None:
+					model.AddChild(gc)
+
+			except raptor_data.InvalidChildError:
+				Raptor.Warn("Can't add child %s to element %s",
+							 child.localName, node.localName)
+
+	# only return a valid object (or raise error)
+	if model.Valid():
+		if model.IsApplicable():
+			return model
+		else:
+			return None
+	else:
+		raise raptor_data.InvalidChildError
+
+
+class SystemModelComponent(generic_path.Path):
+	"""Path sub-class that wraps up a component bld.inf file with
+	system_definition.xml context information."""
+
+	def __init__(self, aBldInfFile, aLayerName, aContainerNames, aSystemDefinitionFile, aSystemDefinitionBase, aSystemDefinitionVersion):
+		generic_path.Path.__init__(self, aBldInfFile.Absolute().path)
+		self.__ContainerNames = aContainerNames
+		self.__LayerName = aLayerName
+		self.__SystemDefinitionFile = aSystemDefinitionFile
+		self.__SystemDefinitionBase = aSystemDefinitionBase
+		self.__SystemDefinitionVersion = aSystemDefinitionVersion
+
+	def GetSystemDefinitionFile(self):
+		return self.__SystemDefinitionFile
+
+	def GetSystemDefinitionBase(self):
+		return self.__SystemDefinitionBase
+
+	def GetSystemDefinitionVersion(self):
+		return self.__SystemDefinitionVersion
+
+	def GetLayerName(self):
+		return self.__LayerName
+
+	def GetContainerName(self, aContainerType):
+		if self.__ContainerNames.has_key(aContainerType):
+			return self.__ContainerNames[aContainerType]
+		return ""
+
+
+class SystemModel(object):
+	"""A representation of the SystemModel section of a Symbian system_definition.xml file."""
+
+	def __init__(self, aLogger, aSystemDefinitionFile, aSystemDefinitionBase):
+		self.__Logger = aLogger
+		self.__SystemDefinitionFile = aSystemDefinitionFile.GetLocalString()
+		self.__SystemDefinitionBase = aSystemDefinitionBase.GetLocalString()
+		self.__Version = {'MAJOR':0,'MID':0,'MINOR':0}
+		self.__IdAttribute = "name"
+		self.__ComponentRoot = ""
+		self.__TotalComponents = 0
+		self.__LayerList = []
+		self.__LayerDetails = {}
+		self.__MissingBldInfs = {}
+
+		self.__DOM = None
+		self.__SystemDefinitionElement = None
+
+		if self.__Read():
+			if self.__Validate():
+				self.__Parse()
+
+		if self.__DOM:
+			self.__DOM.unlink()
+
+	def HasLayer(self, aLayer):
+		return aLayer in self.__LayerList
+
+	def GetLayerNames(self):
+		return self.__LayerList
+
+	def GetLayerComponents(self, aLayer):
+		if not self.HasLayer(aLayer):
+			self.__Logger.Error("System Definition layer \"%s\" does not exist in %s", aLayer, self.__SystemDefinitionFile)
+			return []
+
+		return self.__LayerDetails[aLayer]
+
+	def IsLayerBuildable(self, aLayer):
+		if aLayer in self.__MissingBldInfs:
+			for missingbldinf in self.__MissingBldInfs[aLayer]:
+				self.__Logger.Error("System Definition layer \"%s\" from system definition file \"%s\" " + \
+								    "refers to non existent bld.inf file %s", aLayer, self.__SystemDefinitionFile, missingbldinf)
+
+		if len(self.GetLayerComponents(aLayer)):
+			return True
+		return False
+
+
+	def GetAllComponents(self):
+		components = []
+
+		for layer in self.GetLayerNames():
+			components.extend(self.GetLayerComponents(layer))
+
+		return components
+
+	def DumpLayerInfo(self, aLayer):
+		if self.HasLayer(aLayer):
+			self.__Logger.Info("Found %d bld.inf references in layer \"%s\"", len(self.GetLayerComponents(aLayer)), aLayer)
+
+	def DumpInfo(self):
+		self.__Logger.Info("Found %d bld.inf references in %s within %d layers:", len(self.GetAllComponents()), self.__SystemDefinitionFile, len(self.GetLayerNames()))
+		self.__Logger.Info("\t%s", ", ".join(self.GetLayerNames()))
+		self.__Logger.InfoDiscovery(object_type = "layers",
+				count = len(self.GetLayerNames()))
+		self.__Logger.InfoDiscovery(object_type = "bld.inf references",
+				count = len(self.GetAllComponents()))
+
+	def __Read(self):
+		if not os.path.exists(self.__SystemDefinitionFile):
+			self.__Logger.Error("System Definition file %s does not exist", self.__SystemDefinitionFile)
+			return False
+
+		self.__Logger.Info("System Definition file %s", self.__SystemDefinitionFile)
+
+		# try to read the XML file
+		try:
+			self.__DOM = xml.dom.minidom.parse(self.__SystemDefinitionFile)
+
+		except: # a whole bag of exceptions can be raised here
+			self.__Logger.Error("Failed to parse XML file %s", self.__SystemDefinitionFile)
+			return False
+
+		# <SystemDefinition> is always the root element
+		self.__SystemDefinitionElement = self.__DOM.documentElement
+
+		return True
+
+	def __Validate(self):
+		# account for different schema versions in processing
+		# old format : version >= 1.3.0
+		# new format : version >= 2.0.0 (assume later versions are compatible...at least for now)
+		version = re.match(r'(?P<MAJOR>\d)\.(?P<MID>\d)(\.(?P<MINOR>\d))?', self.__SystemDefinitionElement.getAttribute("schema"))
+
+		if not version:
+			self.__Logger.Error("Cannot determine schema version of XML file %s", self.__SystemDefinitionFile)
+			return False
+
+		self.__Version['MAJOR'] = int(version.group('MAJOR'))
+		self.__Version['MID'] = int(version.group('MID'))
+		self.__Version['MINOR'] = int(version.group('MINOR'))
+
+		if self.__Version['MAJOR'] == 1 and self.__Version['MID'] > 2:
+			self.__ComponentRoot = self.__SystemDefinitionBase
+		elif self.__Version['MAJOR'] == 2 or self.__Version['MAJOR'] == 3:
+			# 2.0.x and 3.0.0 formats support SOURCEROOT or SRCROOT as an environment specified base - we respect this, unless
+			# explicitly overridden on the command line
+			if os.environ.has_key('SRCROOT'):
+				self.__ComponentRoot = generic_path.Path(os.environ['SRCROOT'])
+			elif os.environ.has_key('SOURCEROOT'):
+				self.__ComponentRoot = generic_path.Path(os.environ['SOURCEROOT'])
+
+			if self.__SystemDefinitionBase and self.__SystemDefinitionBase != ".":
+				self.__ComponentRoot = self.__SystemDefinitionBase
+				if os.environ.has_key('SRCROOT'):
+					self.__Logger.Info("Command line specified System Definition file base \'%s\' overriding environment SRCROOT \'%s\'", self.__SystemDefinitionBase, os.environ['SRCROOT'])
+				elif os.environ.has_key('SOURCEROOT'):
+					self.__Logger.Info("Command line specified System Definition file base \'%s\' overriding environment SOURCEROOT \'%s\'", self.__SystemDefinitionBase, os.environ['SOURCEROOT'])
+		else:
+			self.__Logger.Error("Cannot process schema version %s of file %s", version.string, self.__SystemDefinitionFile)
+			return False
+
+		if self.__Version['MAJOR'] >= 3:
+			# id is the unique identifier for 3.0 and later schema
+			self.__IdAttribute = "id"
+
+		return True
+
+	def __Parse(self):
+		# For 2.0 and earlier: find the <systemModel> element (there can be 0 or 1) and search any <layer> elements for <unit> elements with "bldFile" attributes
+		# the <layer> context of captured "bldFile" attributes is recorded as we go
+		# For 3.0 and later, process any architectural topmost element, use the topmost element with an id as the "layer"
+		for child in self.__SystemDefinitionElement.childNodes:
+			if child.localName in ["systemModel", "layer", "package", "collection", "component"]:
+				self.__ProcessSystemModelElement(child)
+
+	def __CreateComponent(self, aBldInfFile, aUnitElement):
+		# take a resolved bld.inf file and associated <unit/> element and returns a populated Component object
+		containers = {}
+		self.__GetElementContainers(aUnitElement, containers)
+		layer = self.__GetEffectiveLayer(aUnitElement)
+		component = SystemModelComponent(aBldInfFile, layer, containers, self.__SystemDefinitionFile, self.__SystemDefinitionBase, self.__Version)
+
+		return component
+
+	def __GetEffectiveLayer(self, aElement):
+		#' return the ID of the topmost item which has an ID. For 1.x and 2.x, this will always be layer, for 3.x, it will be the topmost ID'd element in the file
+		# never call this on the root element
+		if aElement.parentNode.hasAttribute(self.__IdAttribute):
+			return self.__GetEffectiveLayer(aElement.parentNode)
+		elif aElement.hasAttribute(self.__IdAttribute):
+			return aElement.getAttribute(self.__IdAttribute)
+		return ""
+
+	def __GetElementContainers(self, aElement, aContainers):
+		# take a <unit/> element and creates a type->name dictionary of all of its parent containers
+		# We're only interested in parent nodes if they're not the top-most node
+		if aElement.parentNode.parentNode:
+			parent = aElement.parentNode
+			name = parent.getAttribute(self.__IdAttribute)
+
+			if name:
+				aContainers[parent.tagName] = name
+
+			self.__GetElementContainers(parent, aContainers)
+
+	def __ProcessSystemModelElement(self, aElement):
+		"""Search for XML <unit/> elements with 'bldFile' attributes and resolve concrete bld.inf locations
+		with an appreciation of different schema versions."""
+
+		# The effective "layer" is the item whose parent does not have an id (or name in 2.x and earlier)
+		if not aElement.parentNode.hasAttribute(self.__IdAttribute) :
+			currentLayer = aElement.getAttribute(self.__IdAttribute)
+
+			if not self.__LayerDetails.has_key(currentLayer):
+				self.__LayerDetails[currentLayer] = []
+
+			if not currentLayer in self.__LayerList:
+				self.__LayerList.append(currentLayer)
+
+		elif aElement.tagName == "unit" and aElement.hasAttributes():
+			bldFileValue = aElement.getAttribute("bldFile")
+
+			if bldFileValue:
+				bldInfRoot = self.__ComponentRoot
+
+				if self.__Version['MAJOR'] == 1:
+					# version 1.x schema paths can use DOS slashes
+					bldFileValue = raptor_utilities.convertToUnixSlash(bldFileValue)
+				elif self.__Version['MAJOR'] >= 2:
+					# version 2.x.x schema paths are subject to a "root" attribute off-set, if it exists
+					rootValue = aElement.getAttribute("root")
+
+					if rootValue:
+						if os.environ.has_key(rootValue):
+							bldInfRoot = generic_path.Path(os.environ[rootValue])
+						else:
+							# Assume that this is an error i.e. don't attempt to resolve in relation to SOURCEROOT
+							bldInfRoot = None
+							self.__Logger.Error("Cannot resolve \'root\' attribute value \"%s\" in %s", rootValue, self.__SystemDefinitionFile)
+							return
+
+				group = generic_path.Path(bldFileValue)
+
+				if self.__Version['MAJOR'] < 3:
+					# absolute paths are not changed by root var in 1.x and 2.x
+					if not group.isAbsolute() and bldInfRoot:
+						group = generic_path.Join(bldInfRoot, group)
+				else:
+					# only absolute paths are changed by root var in 3.x
+					if group.isAbsolute() and bldInfRoot:
+						group = generic_path.Join(bldInfRoot, group)
+
+				bldinf = generic_path.Join(group, "bld.inf").FindCaseless()
+
+				if bldinf == None:
+					# recording layers containing non existent bld.infs
+					bldinfname = group.GetLocalString()
+					bldinfname = bldinfname + 'bld.inf'
+					layer = self.__GetEffectiveLayer(aElement)
+					if not layer in self.__MissingBldInfs:
+						self.__MissingBldInfs[layer]=[]
+					self.__MissingBldInfs[layer].append(bldinfname)
+
+				else:
+					component = self.__CreateComponent(bldinf, aElement)
+					layer = component.GetLayerName()
+					if layer:
+						self.__LayerDetails[layer].append(component)
+						self.__TotalComponents += 1
+					else:
+						self.__Logger.Error("No containing layer found for %s in %s", str(bldinf), self.__SystemDefinitionFile)
+
+		# search the sub-elements
+		for child in aElement.childNodes:
+			if child.nodeType == child.ELEMENT_NODE:
+				self.__ProcessSystemModelElement(child)
+
+
+# end of the raptor_xml module
--- a/sbsv2/raptor/schema/build/1_0.xsd	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/schema/build/1_0.xsd	Wed Jun 23 16:56:47 2010 +0800
@@ -1,87 +1,87 @@
-<?xml version="1.0"?>
-<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://symbian.com/xml/build" xmlns="http://symbian.com/xml/build" elementFormDefault="qualified">
-
-	<xsd:annotation>
-		<xsd:documentation xml:lang="en">
-			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:
-
-		</xsd:documentation>
-	</xsd:annotation>
-
-	<xsd:element name="build">
-		<xsd:complexType>
-  		<xsd:sequence>
-    		<xsd:element ref="config" minOccurs="0" maxOccurs="unbounded"/>
-				<xsd:element ref="var" minOccurs="0" maxOccurs="unbounded"/>
-			</xsd:sequence>
-		</xsd:complexType>
-	</xsd:element>
-
-	<xsd:element name="config">
-		<xsd:complexType>
-			<xsd:sequence>
-				<xsd:element name="varRef" minOccurs="0" maxOccurs="unbounded">
-					<xsd:complexType>
-						<xsd:attribute name="ref" type="xsd:string"/>
-					</xsd:complexType>
-				</xsd:element>
-				<xsd:element ref="var" minOccurs="0" maxOccurs="unbounded"/>
-				<xsd:element name="configRef" minOccurs="0" maxOccurs="unbounded">
-					<xsd:complexType>
-						<xsd:attribute name="ref" type="xsd:string"/>
-					</xsd:complexType>
-				</xsd:element>
-				<xsd:element ref="config" minOccurs="0" maxOccurs="unbounded"/>
-			</xsd:sequence>
-			<xsd:attribute name="name" type="xsd:string"/>
-			<xsd:attribute name="abstract" type="xsd:boolean"/>
-		</xsd:complexType>
-	</xsd:element>
-
-	<xsd:element name="var">
-		<xsd:complexType>
-			<xsd:sequence maxOccurs="unbounded">
-		  	<xsd:element name="env" minOccurs="0" maxOccurs="unbounded">
-	  			<xsd:complexType>
-		      	<xsd:attribute name="name" type="xsd:string"/>
-		      	<xsd:attribute name="default" type="xsd:string"/>
-		      	<xsd:attribute name="type" type="xsd:string"/>
-						<xsd:attribute name="versionCommand" type="xsd:string"/>
-						<xsd:attribute name="versionResult" type="xsd:string"/>
-		  		</xsd:complexType>
-				</xsd:element>
-				<xsd:element name="set" minOccurs="0" maxOccurs="unbounded">
-					<xsd:complexType>
-						<xsd:attribute name="name" type="xsd:string"/>
-						<xsd:attribute name="value" type="xsd:string"/>
-						<xsd:attribute name="type" type="xsd:string"/>
-						<xsd:attribute name="versionCommand" type="xsd:string"/>
-						<xsd:attribute name="versionResult" type="xsd:string"/>
-					</xsd:complexType>
-				</xsd:element>
-				<xsd:element name="append" minOccurs="0" maxOccurs="unbounded">
-					<xsd:complexType>
-						<xsd:attribute name="name" type="xsd:string"/>
-						<xsd:attribute name="value" type="xsd:string"/>
-						<xsd:attribute name="separator" type="xsd:string"/>
-					</xsd:complexType>
-				</xsd:element>
-			</xsd:sequence>
-			<xsd:attribute name="name" type="xsd:string"/>
-		</xsd:complexType>
-	</xsd:element>
-
-</xsd:schema>
-
+<?xml version="1.0"?>
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://symbian.com/xml/build" xmlns="http://symbian.com/xml/build" elementFormDefault="qualified">
+
+	<xsd:annotation>
+		<xsd:documentation xml:lang="en">
+			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:
+
+		</xsd:documentation>
+	</xsd:annotation>
+
+	<xsd:element name="build">
+		<xsd:complexType>
+  		<xsd:sequence>
+    		<xsd:element ref="config" minOccurs="0" maxOccurs="unbounded"/>
+				<xsd:element ref="var" minOccurs="0" maxOccurs="unbounded"/>
+			</xsd:sequence>
+		</xsd:complexType>
+	</xsd:element>
+
+	<xsd:element name="config">
+		<xsd:complexType>
+			<xsd:sequence>
+				<xsd:element name="varRef" minOccurs="0" maxOccurs="unbounded">
+					<xsd:complexType>
+						<xsd:attribute name="ref" type="xsd:string"/>
+					</xsd:complexType>
+				</xsd:element>
+				<xsd:element ref="var" minOccurs="0" maxOccurs="unbounded"/>
+				<xsd:element name="configRef" minOccurs="0" maxOccurs="unbounded">
+					<xsd:complexType>
+						<xsd:attribute name="ref" type="xsd:string"/>
+					</xsd:complexType>
+				</xsd:element>
+				<xsd:element ref="config" minOccurs="0" maxOccurs="unbounded"/>
+			</xsd:sequence>
+			<xsd:attribute name="name" type="xsd:string"/>
+			<xsd:attribute name="abstract" type="xsd:boolean"/>
+		</xsd:complexType>
+	</xsd:element>
+
+	<xsd:element name="var">
+		<xsd:complexType>
+			<xsd:sequence maxOccurs="unbounded">
+		  	<xsd:element name="env" minOccurs="0" maxOccurs="unbounded">
+	  			<xsd:complexType>
+		      	<xsd:attribute name="name" type="xsd:string"/>
+		      	<xsd:attribute name="default" type="xsd:string"/>
+		      	<xsd:attribute name="type" type="xsd:string"/>
+						<xsd:attribute name="versionCommand" type="xsd:string"/>
+						<xsd:attribute name="versionResult" type="xsd:string"/>
+		  		</xsd:complexType>
+				</xsd:element>
+				<xsd:element name="set" minOccurs="0" maxOccurs="unbounded">
+					<xsd:complexType>
+						<xsd:attribute name="name" type="xsd:string"/>
+						<xsd:attribute name="value" type="xsd:string"/>
+						<xsd:attribute name="type" type="xsd:string"/>
+						<xsd:attribute name="versionCommand" type="xsd:string"/>
+						<xsd:attribute name="versionResult" type="xsd:string"/>
+					</xsd:complexType>
+				</xsd:element>
+				<xsd:element name="append" minOccurs="0" maxOccurs="unbounded">
+					<xsd:complexType>
+						<xsd:attribute name="name" type="xsd:string"/>
+						<xsd:attribute name="value" type="xsd:string"/>
+						<xsd:attribute name="separator" type="xsd:string"/>
+					</xsd:complexType>
+				</xsd:element>
+			</xsd:sequence>
+			<xsd:attribute name="name" type="xsd:string"/>
+		</xsd:complexType>
+	</xsd:element>
+
+</xsd:schema>
+
--- a/sbsv2/raptor/schema/build/2_0.xsd	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/schema/build/2_0.xsd	Wed Jun 23 16:56:47 2010 +0800
@@ -1,134 +1,134 @@
-<?xml version="1.0"?>
-<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://symbian.com/xml/build" targetNamespace="http://symbian.com/xml/build" elementFormDefault="qualified">
-	<xsd:annotation>
-		<xsd:documentation xml:lang="en">
-			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:
-
-		</xsd:documentation>
-	</xsd:annotation>
-	<xsd:element name="build">
-		<xsd:complexType>
-			<xsd:sequence maxOccurs="unbounded">
-				<xsd:element ref="var" minOccurs="0" maxOccurs="unbounded"/>
-				<xsd:element ref="alias" minOccurs="0" maxOccurs="unbounded"/>
-				<xsd:element ref="group" minOccurs="0" maxOccurs="unbounded"/>
-				<xsd:element ref="interface" minOccurs="0" maxOccurs="unbounded"/>
-			</xsd:sequence>
-		</xsd:complexType>
-	</xsd:element>
-	<xsd:element name="var">
-		<xsd:complexType>
-			<xsd:sequence>
-				<xsd:sequence minOccurs="0">
-					<xsd:element ref="varRef" minOccurs="0" maxOccurs="unbounded"/>
-				</xsd:sequence>
-				<xsd:sequence maxOccurs="unbounded">
-					<xsd:element name="env" minOccurs="0" maxOccurs="unbounded">
-						<xsd:complexType>
-							<xsd:attribute name="name" type="xsd:string" use="required"/>
-							<xsd:attribute name="default" type="xsd:string" use="optional"/>
-							<xsd:attribute name="type" type="xsd:string"/>
-							<xsd:attribute name="versionCommand" type="xsd:string"/>
-							<xsd:attribute name="versionResult" type="xsd:string"/>
-						</xsd:complexType>
-					</xsd:element>
-					<xsd:element name="set" minOccurs="0" maxOccurs="unbounded">
-						<xsd:complexType>
-							<xsd:attribute name="name" type="xsd:string" use="required"/>
-							<xsd:attribute name="value" type="xsd:string" use="required"/>
-							<xsd:attribute name="type" type="xsd:string"/>
-							<xsd:attribute name="versionCommand" type="xsd:string"/>
-							<xsd:attribute name="versionResult" type="xsd:string"/>
-							<xsd:attribute name="host" type="xsd:string"/>
-						</xsd:complexType>
-					</xsd:element>
-					<xsd:element name="append" minOccurs="0" maxOccurs="unbounded">
-						<xsd:complexType>
-							<xsd:attribute name="name" type="xsd:string" use="required"/>
-							<xsd:attribute name="value" type="xsd:string" use="required"/>
-							<xsd:attribute name="separator" type="xsd:string"/>
-						</xsd:complexType>
-					</xsd:element>
-					<xsd:element name="prepend" minOccurs="0" maxOccurs="unbounded">
-						<xsd:complexType>
-							<xsd:attribute name="name" type="xsd:string" use="required"/>
-							<xsd:attribute name="value" type="xsd:string" use="required"/>
-							<xsd:attribute name="separator" type="xsd:string"/>
-						</xsd:complexType>
-					</xsd:element>
-				</xsd:sequence>
-			</xsd:sequence>
-			<xsd:attribute name="name" type="xsd:string" use="required"/>
-			<xsd:attribute name="extends" type="xsd:string"/>
-			<xsd:attribute name="host" type="xsd:string"/>
-		</xsd:complexType>
-	</xsd:element>
-	<xsd:element name="alias">
-		<xsd:complexType>
-			<xsd:attribute name="name" type="xsd:string" use="required"/>
-			<xsd:attribute name="meaning" type="xsd:string" use="required"/>
-		</xsd:complexType>
-	</xsd:element>
-	<xsd:element name="group">
-		<xsd:complexType>
-			<xsd:sequence maxOccurs="unbounded">
-				<xsd:element ref="varRef" minOccurs="0" maxOccurs="unbounded"/>
-				<xsd:element ref="aliasRef" minOccurs="0" maxOccurs="unbounded"/>
-				<xsd:element ref="groupRef" minOccurs="0" maxOccurs="unbounded"/>
-			</xsd:sequence>
-			<xsd:attribute name="name" use="required"/>
-		</xsd:complexType>
-	</xsd:element>
-	<xsd:element name="varRef">
-		<xsd:complexType>
-			<xsd:attribute name="ref" type="xsd:string" use="required"/>
-			<xsd:attribute name="mod" type="xsd:string"/>
-		</xsd:complexType>
-	</xsd:element>
-	<xsd:element name="aliasRef">
-		<xsd:complexType>
-			<xsd:attribute name="ref" type="xsd:string" use="required"/>
-			<xsd:attribute name="mod" type="xsd:string"/>
-		</xsd:complexType>
-	</xsd:element>
-	<xsd:element name="groupRef">
-		<xsd:complexType>
-			<xsd:attribute name="ref" type="xsd:string" use="required"/>
-			<xsd:attribute name="mod" type="xsd:string"/>
-		</xsd:complexType>
-	</xsd:element>
-	<xsd:element name="interface">
-		<xsd:complexType>
-			<xsd:sequence minOccurs="0" maxOccurs="unbounded">
-				<xsd:element name="param" minOccurs="0" maxOccurs="unbounded">
-					<xsd:complexType>
-						<xsd:attribute name="name" type="xsd:string" use="required"/>
-						<xsd:attribute name="default" type="xsd:string"/>
-					</xsd:complexType>
-				</xsd:element>
-				<xsd:element name="paramgroup" minOccurs="0" maxOccurs="unbounded">
-					<xsd:complexType>
-						<xsd:attribute name="pattern" type="xsd:string" use="required"/>
-						<xsd:attribute name="default" type="xsd:string"/>
-					</xsd:complexType>
-				</xsd:element>
-			</xsd:sequence>
-			<xsd:attribute name="name" type="xsd:string" use="required"/>
-			<xsd:attribute name="extends" type="xsd:string"/>
-			<xsd:attribute name="abstract" type="xsd:boolean"/>
-			<xsd:attribute name="flm" type="xsd:string"/>
-		</xsd:complexType>
-	</xsd:element>
-</xsd:schema>
+<?xml version="1.0"?>
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://symbian.com/xml/build" targetNamespace="http://symbian.com/xml/build" elementFormDefault="qualified">
+	<xsd:annotation>
+		<xsd:documentation xml:lang="en">
+			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:
+
+		</xsd:documentation>
+	</xsd:annotation>
+	<xsd:element name="build">
+		<xsd:complexType>
+			<xsd:sequence maxOccurs="unbounded">
+				<xsd:element ref="var" minOccurs="0" maxOccurs="unbounded"/>
+				<xsd:element ref="alias" minOccurs="0" maxOccurs="unbounded"/>
+				<xsd:element ref="group" minOccurs="0" maxOccurs="unbounded"/>
+				<xsd:element ref="interface" minOccurs="0" maxOccurs="unbounded"/>
+			</xsd:sequence>
+		</xsd:complexType>
+	</xsd:element>
+	<xsd:element name="var">
+		<xsd:complexType>
+			<xsd:sequence>
+				<xsd:sequence minOccurs="0">
+					<xsd:element ref="varRef" minOccurs="0" maxOccurs="unbounded"/>
+				</xsd:sequence>
+				<xsd:sequence maxOccurs="unbounded">
+					<xsd:element name="env" minOccurs="0" maxOccurs="unbounded">
+						<xsd:complexType>
+							<xsd:attribute name="name" type="xsd:string" use="required"/>
+							<xsd:attribute name="default" type="xsd:string" use="optional"/>
+							<xsd:attribute name="type" type="xsd:string"/>
+							<xsd:attribute name="versionCommand" type="xsd:string"/>
+							<xsd:attribute name="versionResult" type="xsd:string"/>
+						</xsd:complexType>
+					</xsd:element>
+					<xsd:element name="set" minOccurs="0" maxOccurs="unbounded">
+						<xsd:complexType>
+							<xsd:attribute name="name" type="xsd:string" use="required"/>
+							<xsd:attribute name="value" type="xsd:string" use="required"/>
+							<xsd:attribute name="type" type="xsd:string"/>
+							<xsd:attribute name="versionCommand" type="xsd:string"/>
+							<xsd:attribute name="versionResult" type="xsd:string"/>
+							<xsd:attribute name="host" type="xsd:string"/>
+						</xsd:complexType>
+					</xsd:element>
+					<xsd:element name="append" minOccurs="0" maxOccurs="unbounded">
+						<xsd:complexType>
+							<xsd:attribute name="name" type="xsd:string" use="required"/>
+							<xsd:attribute name="value" type="xsd:string" use="required"/>
+							<xsd:attribute name="separator" type="xsd:string"/>
+						</xsd:complexType>
+					</xsd:element>
+					<xsd:element name="prepend" minOccurs="0" maxOccurs="unbounded">
+						<xsd:complexType>
+							<xsd:attribute name="name" type="xsd:string" use="required"/>
+							<xsd:attribute name="value" type="xsd:string" use="required"/>
+							<xsd:attribute name="separator" type="xsd:string"/>
+						</xsd:complexType>
+					</xsd:element>
+				</xsd:sequence>
+			</xsd:sequence>
+			<xsd:attribute name="name" type="xsd:string" use="required"/>
+			<xsd:attribute name="extends" type="xsd:string"/>
+			<xsd:attribute name="host" type="xsd:string"/>
+		</xsd:complexType>
+	</xsd:element>
+	<xsd:element name="alias">
+		<xsd:complexType>
+			<xsd:attribute name="name" type="xsd:string" use="required"/>
+			<xsd:attribute name="meaning" type="xsd:string" use="required"/>
+		</xsd:complexType>
+	</xsd:element>
+	<xsd:element name="group">
+		<xsd:complexType>
+			<xsd:sequence maxOccurs="unbounded">
+				<xsd:element ref="varRef" minOccurs="0" maxOccurs="unbounded"/>
+				<xsd:element ref="aliasRef" minOccurs="0" maxOccurs="unbounded"/>
+				<xsd:element ref="groupRef" minOccurs="0" maxOccurs="unbounded"/>
+			</xsd:sequence>
+			<xsd:attribute name="name" use="required"/>
+		</xsd:complexType>
+	</xsd:element>
+	<xsd:element name="varRef">
+		<xsd:complexType>
+			<xsd:attribute name="ref" type="xsd:string" use="required"/>
+			<xsd:attribute name="mod" type="xsd:string"/>
+		</xsd:complexType>
+	</xsd:element>
+	<xsd:element name="aliasRef">
+		<xsd:complexType>
+			<xsd:attribute name="ref" type="xsd:string" use="required"/>
+			<xsd:attribute name="mod" type="xsd:string"/>
+		</xsd:complexType>
+	</xsd:element>
+	<xsd:element name="groupRef">
+		<xsd:complexType>
+			<xsd:attribute name="ref" type="xsd:string" use="required"/>
+			<xsd:attribute name="mod" type="xsd:string"/>
+		</xsd:complexType>
+	</xsd:element>
+	<xsd:element name="interface">
+		<xsd:complexType>
+			<xsd:sequence minOccurs="0" maxOccurs="unbounded">
+				<xsd:element name="param" minOccurs="0" maxOccurs="unbounded">
+					<xsd:complexType>
+						<xsd:attribute name="name" type="xsd:string" use="required"/>
+						<xsd:attribute name="default" type="xsd:string"/>
+					</xsd:complexType>
+				</xsd:element>
+				<xsd:element name="paramgroup" minOccurs="0" maxOccurs="unbounded">
+					<xsd:complexType>
+						<xsd:attribute name="pattern" type="xsd:string" use="required"/>
+						<xsd:attribute name="default" type="xsd:string"/>
+					</xsd:complexType>
+				</xsd:element>
+			</xsd:sequence>
+			<xsd:attribute name="name" type="xsd:string" use="required"/>
+			<xsd:attribute name="extends" type="xsd:string"/>
+			<xsd:attribute name="abstract" type="xsd:boolean"/>
+			<xsd:attribute name="flm" type="xsd:string"/>
+		</xsd:complexType>
+	</xsd:element>
+</xsd:schema>
--- a/sbsv2/raptor/schema/build/log/1_0.xsd	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/schema/build/log/1_0.xsd	Wed Jun 23 16:56:47 2010 +0800
@@ -1,79 +1,80 @@
-<?xml version="1.0"?>
-<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://symbian.com/xml/build/log" xmlns="http://symbian.com/xml/build/log" elementFormDefault="qualified">
-
-	<xsd:annotation>
-		<xsd:documentation xml:lang="en">
-			Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
-			All rights reserved.
-			This component and the accompanying materials are made available
-			uunder the terms of the License "Eclipse Public License v1.0"
-			which accompanies this distribution, and is available
-			at the URL "http://www.eclipse.org/legal/epl-v10.html".
-
-			Initial Contributors:
-			Nokia Corporation - initial contribution.
-
-			Contributors:
-
-			Description:
-
-		</xsd:documentation>
-	</xsd:annotation>
-
-	<xsd:element name="buildlog">
-		<xsd:complexType mixed="true">
-			<xsd:sequence maxOccurs="unbounded">
-				<xsd:element name="info" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
-				<xsd:element name="error" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
-				<xsd:element name="warning" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
-				<xsd:element name="flm" type="flmType" minOccurs="0" maxOccurs="unbounded"/>
-				<xsd:element name="bmconvcmdfile" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
-				<xsd:element name="recipe" type="recipeType" minOccurs="0" maxOccurs="unbounded"/>
-			</xsd:sequence>
-			<xsd:attribute name="sbs_version" type="xsd:string"/>
-		</xsd:complexType>
-	</xsd:element>
-
-	<xsd:complexType name="flmType" mixed="true">
-		<xsd:attribute name="name" type="xsd:string"/>
-		<xsd:attribute name="target" type="xsd:string"/>
-		<xsd:attribute name="EPOCROOT" type="xsd:string"/>
-		<xsd:attribute name="type" type="xsd:string"/>
-		<xsd:attribute name="variant" type="xsd:string"/>
-		<xsd:attribute name="component" type="xsd:string"/>
-		<xsd:attribute name="project" type="xsd:string"/>
-		<xsd:attribute name="source" type="xsd:string"/>
-	</xsd:complexType>
-
-	<xsd:complexType name="recipeType" mixed="true">
-		<xsd:sequence>
-		  <xsd:element name="time">
-	  		<xsd:complexType>
-		      <xsd:attribute name="start" type="xsd:decimal"/>
-		      <xsd:attribute name="elapsed" type="xsd:decimal"/>
-		    </xsd:complexType>
-			</xsd:element>
-			<xsd:element name="status">
-				<xsd:complexType>
-					<xsd:attribute name="exit" type="xsd:string"/>
-					<xsd:attribute name="code" type="xsd:integer"/>
-					<xsd:attribute name="name" type="xsd:string"/>
-					<xsd:attribute name="project" type="xsd:string"/>
-					<xsd:attribute name="component" type="xsd:string"/>
-					<xsd:attribute name="forcesuccess" type="xsd:string"/>
-				</xsd:complexType>
-			</xsd:element>
-		</xsd:sequence>
-		<xsd:attribute name="name" type="xsd:string"/>
-		<xsd:attribute name="host" type="xsd:string"/>
-		<xsd:attribute name="layer" type="xsd:string"/>
-		<xsd:attribute name="component" type="xsd:string"/>
-		<xsd:attribute name="bldinf" type="xsd:string"/>
-		<xsd:attribute name="mmp" type="xsd:string"/>
-		<xsd:attribute name="config" type="xsd:string"/>
-		<xsd:attribute name="platform" type="xsd:string"/>
-		<xsd:attribute name="phase" type="xsd:string"/>
-	</xsd:complexType>
-
-</xsd:schema>
-
+<?xml version="1.0"?>
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://symbian.com/xml/build/log" xmlns="http://symbian.com/xml/build/log" elementFormDefault="qualified">
+
+	<xsd:annotation>
+		<xsd:documentation xml:lang="en">
+			Copyright (c) 2008-2010 Nokia Corporation and/or its subsidiary(-ies).
+			All rights reserved.
+			This component and the accompanying materials are made available
+			uunder the terms of the License "Eclipse Public License v1.0"
+			which accompanies this distribution, and is available
+			at the URL "http://www.eclipse.org/legal/epl-v10.html".
+
+			Initial Contributors:
+			Nokia Corporation - initial contribution.
+
+			Contributors:
+
+			Description:
+
+		</xsd:documentation>
+	</xsd:annotation>
+
+	<xsd:element name="buildlog">
+		<xsd:complexType mixed="true">
+			<xsd:sequence maxOccurs="unbounded">
+				<xsd:element name="info" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
+				<xsd:element name="error" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
+				<xsd:element name="warning" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
+				<xsd:element name="flm" type="flmType" minOccurs="0" maxOccurs="unbounded"/>
+				<xsd:element name="bmconvcmdfile" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
+				<xsd:element name="recipe" type="recipeType" minOccurs="0" maxOccurs="unbounded"/>
+			</xsd:sequence>
+			<xsd:attribute name="sbs_version" type="xsd:string"/>
+		</xsd:complexType>
+	</xsd:element>
+
+	<xsd:complexType name="flmType" mixed="true">
+		<xsd:attribute name="name" type="xsd:string"/>
+		<xsd:attribute name="target" type="xsd:string"/>
+		<xsd:attribute name="EPOCROOT" type="xsd:string"/>
+		<xsd:attribute name="type" type="xsd:string"/>
+		<xsd:attribute name="variant" type="xsd:string"/>
+		<xsd:attribute name="component" type="xsd:string"/>
+		<xsd:attribute name="project" type="xsd:string"/>
+		<xsd:attribute name="source" type="xsd:string"/>
+	</xsd:complexType>
+
+	<xsd:complexType name="recipeType" mixed="true">
+		<xsd:sequence>
+		  <xsd:element name="time">
+	  		<xsd:complexType>
+		      <xsd:attribute name="start" type="xsd:decimal"/>
+		      <xsd:attribute name="elapsed" type="xsd:decimal"/>
+		    </xsd:complexType>
+			</xsd:element>
+			<xsd:element name="status">
+				<xsd:complexType>
+					<xsd:attribute name="exit" type="xsd:string"/>
+					<xsd:attribute name="code" type="xsd:integer"/>
+					<xsd:attribute name="name" type="xsd:string"/>
+					<xsd:attribute name="project" type="xsd:string"/>
+					<xsd:attribute name="component" type="xsd:string"/>
+					<xsd:attribute name="flags" type="xsd:string"/>
+					<xsd:attribute name="reason" type="xsd:string"/>
+				</xsd:complexType>
+			</xsd:element>
+		</xsd:sequence>
+		<xsd:attribute name="name" type="xsd:string"/>
+		<xsd:attribute name="host" type="xsd:string"/>
+		<xsd:attribute name="layer" type="xsd:string"/>
+		<xsd:attribute name="component" type="xsd:string"/>
+		<xsd:attribute name="bldinf" type="xsd:string"/>
+		<xsd:attribute name="mmp" type="xsd:string"/>
+		<xsd:attribute name="config" type="xsd:string"/>
+		<xsd:attribute name="platform" type="xsd:string"/>
+		<xsd:attribute name="phase" type="xsd:string"/>
+	</xsd:complexType>
+
+</xsd:schema>
+
--- a/sbsv2/raptor/util/Makefile	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/Makefile	Wed Jun 23 16:56:47 2010 +0800
@@ -1,67 +1,67 @@
-
-# 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:
-##
-
-
-SHELL:=bash
-
-.PHONY:: all
-all::
-
-include utilbuild.mk # need general settings e.g. INSTALLROOT
-
-ifeq ($(filter CLEAN,$(MAKECMDGOALS))$(filter clean,$(MAKECMDGOALS)),)
-
-include gccprogram.mk
-
-# Actual programs
-include descramble/Makefile
-
-include talon/Makefile
-
-include ransleep/Makefile
-
-# Some tools not built for windows
-ifneq ($(filter $(HOSTPLATFORM),win),win)
-ifeq ($(CLEANMODE),)
-include bash.mk
-
-include make.mk
-
-#  Build pvm and pvmgmake later when they have been corrected
-#include pvmgmake.mk
-
-#include pvm.mk
-
-include python.mk
-
-include codewarrior.mk
-
-include bvcpp.mk
-
-include gccxml.mk
-
-include dialog.mk
-endif
-
-endif
-
-else
-
-
-clean:
-	@echo "Cleaning"
-	make $(MAKEFILE) CLEANMODE:=1 | grep '<file>' |sed -r 's#.*<file>(.*)</file>.*#\1#' | (read F; while [ $$? -eq 0 ]; do rm -f "$$F"; read F; done; true )
-endif
+
+# 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:
+##
+
+
+SHELL:=bash
+
+.PHONY:: all
+all::
+
+include utilbuild.mk # need general settings e.g. INSTALLROOT
+
+ifeq ($(filter CLEAN,$(MAKECMDGOALS))$(filter clean,$(MAKECMDGOALS)),)
+
+include gccprogram.mk
+
+# Actual programs
+include descramble/Makefile
+
+include talon/Makefile
+
+include ransleep/Makefile
+
+# Some tools not built for windows
+ifneq ($(filter $(HOSTPLATFORM),win),win)
+ifeq ($(CLEANMODE),)
+include bash.mk
+
+include make.mk
+
+#  Build pvm and pvmgmake later when they have been corrected
+#include pvmgmake.mk
+
+#include pvm.mk
+
+include python.mk
+
+include codewarrior.mk
+
+include bvcpp.mk
+
+include gccxml.mk
+
+include dialog.mk
+endif
+
+endif
+
+else
+
+
+clean:
+	@echo "Cleaning"
+	make $(MAKEFILE) CLEANMODE:=1 | grep '<file>' |sed -r 's#.*<file>(.*)</file>.*#\1#' | (read F; while [ $$? -eq 0 ]; do rm -f "$$F"; read F; done; true )
+endif
--- a/sbsv2/raptor/util/bash.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/bash.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,47 +1,47 @@
-#
-# 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: 
-# Build bash 3.2 for SBSv2
-#
-
-
-RAPTOR_BASH_VER:=4.0
-
-BASH_SOURCEDIR:=$(OUTPUTPATH)/bash-$(RAPTOR_BASH_VER)
-BASH_TAR:=$(SBS_HOME)/util/ext/bash-$(RAPTOR_BASH_VER).tar.gz
-BASH_PATCHES_TAR:=$(SBS_HOME)/util/ext/bash-$(RAPTOR_BASH_VER)-patches.tar.gz
-
-define b_bash
-.PHONY:: bash
-
-all:: bash 
-
-bash: $(INSTALLROOT)/bin/bash
-
-$(INSTALLROOT)/bin/bash: $(BASH_TAR) $(BASH_PATCHES_TAR)
-	rm -rf $(BASH_SOURCEDIR) && \
-	cd $(OUTPUTPATH) && \
-	tar -xzf $(BASH_TAR) &&  \
-	(  \
-	cd $(BASH_SOURCEDIR) && \
-	mkdir patches && (cd patches && tar -xzf $(BASH_PATCHES_TAR)) && \
-	for p in patches/*; do if [ -f $p ]; then patch -p0 < $$$$p; fi; done && \
-	CFLAGS="-O2 $(GCCTUNE) -s" ./configure --prefix=$(INSTALLROOT) --enable-arith-for-command --enable-multibyte --enable-job-control --enable-progcomp --enable-process-substitution  --enable-readline --disable-rpath && \
-	$(MAKE) && $(MAKE) install \
-	) ; \
-	cp $$@ $$(dir $$@)/sh
-	
-endef
-
-$(eval $(b_bash))
+#
+# 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: 
+# Build bash 3.2 for SBSv2
+#
+
+
+RAPTOR_BASH_VER:=4.0
+
+BASH_SOURCEDIR:=$(OUTPUTPATH)/bash-$(RAPTOR_BASH_VER)
+BASH_TAR:=$(SBS_HOME)/util/ext/bash-$(RAPTOR_BASH_VER).tar.gz
+BASH_PATCHES_TAR:=$(SBS_HOME)/util/ext/bash-$(RAPTOR_BASH_VER)-patches.tar.gz
+
+define b_bash
+.PHONY:: bash
+
+all:: bash 
+
+bash: $(INSTALLROOT)/bin/bash
+
+$(INSTALLROOT)/bin/bash: $(BASH_TAR) $(BASH_PATCHES_TAR)
+	rm -rf $(BASH_SOURCEDIR) && \
+	cd $(OUTPUTPATH) && \
+	tar -xzf $(BASH_TAR) &&  \
+	(  \
+	cd $(BASH_SOURCEDIR) && \
+	mkdir patches && (cd patches && tar -xzf $(BASH_PATCHES_TAR)) && \
+	for p in patches/*; do if [ -f $p ]; then patch -p0 < $$$$p; fi; done && \
+	CFLAGS="-O2 $(GCCTUNE) -s" ./configure --prefix=$(INSTALLROOT) --enable-arith-for-command --enable-multibyte --enable-job-control --enable-progcomp --enable-process-substitution  --enable-readline --disable-rpath && \
+	$(MAKE) && $(MAKE) install \
+	) ; \
+	cp $$@ $$(dir $$@)/sh
+	
+endef
+
+$(eval $(b_bash))
--- a/sbsv2/raptor/util/bvcpp.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/bvcpp.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,40 +1,40 @@
-#
-# 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: 
-# Utility makefile 
-#
-
-BVCPP_TAR:=$(SBS_HOME)/util/ext/bv.tgz
-
-
-define b_bvcpp
-
-.PHONY:: bvcpp
-
-all:: bvcpp
-
-bvcpp: $(INSTALLROOT)/bv/bin/cpp
-
-$(INSTALLROOT)/bv/bin/cpp: $(BVCPP_TAR)
-	cd $(INSTALLROOT) && \
-	rm -rf bv && \
-	tar -xzf $(BVCPP_TAR)&& touch $$@
-
-endef
-
-$(eval $(b_bvcpp))
-
-
-
-
+#
+# 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: 
+# Utility makefile 
+#
+
+BVCPP_TAR:=$(SBS_HOME)/util/ext/bv.tgz
+
+
+define b_bvcpp
+
+.PHONY:: bvcpp
+
+all:: bvcpp
+
+bvcpp: $(INSTALLROOT)/bv/bin/cpp
+
+$(INSTALLROOT)/bv/bin/cpp: $(BVCPP_TAR)
+	cd $(INSTALLROOT) && \
+	rm -rf bv && \
+	tar -xzf $(BVCPP_TAR)&& touch $$@
+
+endef
+
+$(eval $(b_bvcpp))
+
+
+
+
--- a/sbsv2/raptor/util/codewarrior.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/codewarrior.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,38 +1,38 @@
-#
-# 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: 
-# Utility makefile 
-#
-
-CODEWARRIOR_TAR:=$(SBS_HOME)/util/ext/cw_build470msl19.tgz
-
-
-define b_codewarrior
-
-.PHONY:: codewarrior
-
-all:: codewarrior
-
-codewarrior: $(INSTALLROOT)/cw_build470msl19/release/Symbian_Tools/Command_Line_Tools/mwccsym2
-	
-$(INSTALLROOT)/cw_build470msl19/release/Symbian_Tools/Command_Line_Tools/mwccsym2: $(CODEWARRIOR_TAR)
-	cd $(INSTALLROOT) && \
-	tar -xzf $(CODEWARRIOR_TAR) && touch $$@
-endef
-
-$(eval $(b_codewarrior))
-
-
-
-
+#
+# 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: 
+# Utility makefile 
+#
+
+CODEWARRIOR_TAR:=$(SBS_HOME)/util/ext/cw_build470msl19.tgz
+
+
+define b_codewarrior
+
+.PHONY:: codewarrior
+
+all:: codewarrior
+
+codewarrior: $(INSTALLROOT)/cw_build470msl19/release/Symbian_Tools/Command_Line_Tools/mwccsym2
+	
+$(INSTALLROOT)/cw_build470msl19/release/Symbian_Tools/Command_Line_Tools/mwccsym2: $(CODEWARRIOR_TAR)
+	cd $(INSTALLROOT) && \
+	tar -xzf $(CODEWARRIOR_TAR) && touch $$@
+endef
+
+$(eval $(b_codewarrior))
+
+
+
+
--- a/sbsv2/raptor/util/config.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/config.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,29 +1,30 @@
-/*
-* 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: 
-*
-*/
-
-#ifdef HOST_WIN
-#define HAS_SETENVIRONMENTVARIABLE 1
-#define HAS_GETENVIRONMENTVARIABLE 1
-#define HAS_GETCOMMANDLINE 1
-#define HAS_MILLISECONDSLEEP 1
-#define HAS_MSVCRT 1
-#else
-#define HAS_POLL 1
-#define HAS_SETENV 1
-#define HAS_GETENV 1
-#define HAS_STDLIBH 1
-#endif
+/*
+* Copyright (c) 2009-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: 
+*
+*/
+
+#ifdef HOST_WIN
+#define HAS_SETENVIRONMENTVARIABLE 1
+#define HAS_GETENVIRONMENTVARIABLE 1
+#define HAS_GETCOMMANDLINE 1
+#define HAS_MILLISECONDSLEEP 1
+#define HAS_MSVCRT 1
+#define HAS_WINSOCK2 1
+#else
+#define HAS_POLL 1
+#define HAS_SETENV 1
+#define HAS_GETENV 1
+#define HAS_STDLIBH 1
+#endif
--- a/sbsv2/raptor/util/descramble/Makefile	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/descramble/Makefile	Wed Jun 23 16:56:47 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:
-# Utility makefile 
-#
-#
-
-TARGET:=sbs_descramble
-SOURCES:=$(SBS_HOME:\=/)/util/descramble/descramble.cpp 
-
-ifeq ($(filter win,$(HOSTPLATFORM)),win)
-CFLAGS:=-DWIN32
-LDFLAGS:=
-else
-CFLAGS:=
-LDFLAGS:=-lpthread
-endif
-
-$(eval $(cppprogram))
+# 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:
+# Utility makefile 
+#
+#
+
+TARGET:=sbs_descramble
+SOURCES:=$(SBS_HOME:\=/)/util/descramble/descramble.cpp 
+
+ifeq ($(filter win,$(HOSTPLATFORM)),win)
+CFLAGS:=-DWIN32
+LDFLAGS:=
+else
+CFLAGS:=
+LDFLAGS:=-lpthread
+endif
+
+$(eval $(cppprogram))
--- a/sbsv2/raptor/util/descramble/descramble.cpp	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/descramble/descramble.cpp	Wed Jun 23 16:56:47 2010 +0800
@@ -1,629 +1,629 @@
-/*
-* 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: 
-*
-*/
-
-
-/*
- 	descramble.cpp:
-
-	Description
-	-----------
-	"descramble" is a program that buffers standard input until end of file
-	and then copies the buffers to the standard output in such a way that
-	if there are many copies of descramble running, each will be given an
-	opportunity to write the complete contents of its buffers while the
-	others wait.
-
-	Purpose
-	-------
-	descramble is used to ensure that output from multiple concurrent processes
-	is not interleaved.  It is useful in build systems such as GNU make with
-	the -j switch, although it requires that makefiles are changed before it can
-	work.
-
-	Design
-	------
-	This program may be built on Linux or on Windows.  On both platforms the
-	basic behavior is similar:
-		1) Read standard input into buffers.  Allocate these dynamically
-		   so that there is no limit.
-		2) Wait on a named or system-wide semaphore.
-		3) Output all the buffers to stdout.
-
-	The name of the semaphore is a parameter and should be chosen so that multiple
-	instances of the build system (or whatever process is running many tasks with
-	descramble) cannot block each other.
-
-
-	Special Considerations for Linux
-	--------------------------------
-	A named semaphore is a file in the filesystem.  It is not automatically removed
-	when a process exits.  descramble provides a "stop" parameter to be run at the
-	"end" of the build system (or other process) that will clean away this semaphore.
-
-
-	Special Considerations for Windows
-	----------------------------------
-	The windows implementation is built with the MINGW toolchain.  On windows
-	problems have been noticed that require a fairly complex timeout capability
-	such that descramble will not wait "forever" for output from stdin.
-	This solution currently uses a "kill thread" that will stop descramble if
-	it is blocked in a read on stdio for more than the timeout period.
-
-	The "kill thread" attempts to print as much of the input from stdin as has
-	been read so far.  It scans this for XML characters and escapes them, finally
-	printing its own XML-formatted error message with the escaped version of the
-	input between <descramble> tags.
-
-
-
-
-*/
-
-#include <stdio.h>
-#include <vector>
-#include <ctype.h>
-
-// what size chunks to allocate/read
-const int BufferSize = 4096;
-unsigned int globalreadcounter = 0;
-
-// OS specific headers
-#ifdef WIN32
-#include <windows.h>
-#include <tlhelp32.h>
-#include <fcntl.h> /*  _O_BINARY */
-#else
-#include <stdlib.h>
-#include <fcntl.h>
-#include <semaphore.h>
-#include <sys/types.h>
-#include <signal.h>
-#include <string.h>
-#endif
-#include <unistd.h>
-
-#define DEFAULT_TIMEOUT (600000) // 10 minutes
-
-#define GOOD_OUTPUT 1
-#define BAD_OUTPUT 0
-
-typedef struct
-{
-	char *name;
-	#ifdef WIN32
- 		HANDLE handle;
-	#else
-		sem_t *handle;
-	#endif
-
-	unsigned int timeout;
-} sbs_semaphore;
-
-
-// readstate is a flag to indicate whether descramble is reading
-// it's standard input.
-// This allows the timeout thread on Windows to only cause the
-// process to exit if there is an overdue read operation on the
-// standard input.
-int readstate=1;
-int timeoutstate=0;
-
-// The output semaphore.
-sbs_semaphore sem;
-#ifdef WIN32
-	HANDLE bufferMutex;
-
-
-	// Make all output handling binary
-	unsigned int _CRT_fmode = _O_BINARY;
-
-
-	DWORD killPIDTree = 0;
-#else
-	pid_t killPIDTree = 0;
-#endif
-
-
-
-// Where we store all the standard input.
-std::vector<char*> buffers;
-std::vector<int> bytesIn;
-
-
-void error(const char *reason, char *SEM_NAME)
-{
-	fprintf(stderr, "<descrambler reason='%s' semaphore='%s' />\n", reason, SEM_NAME);
-	exit(1);
-}
-
-#ifdef WIN32
-
-void killProcess(DWORD pid)
-{
-	HANDLE proc = OpenProcess(PROCESS_TERMINATE,0,pid);
-	if (proc)
-	{
-		TerminateProcess(proc, 1);
-		//fprintf(stdout,"sent terminate to process=%d\n", pid);
-		CloseHandle(proc);
-	}
-	else
-	{
-		//fprintf(stderr,"Can't open process=%d\n", pid);
-	}
-}
-
-typedef struct {
-	DWORD PID;
-	DWORD PPID;
-} proc;
-
-void killProcessTreeRecursively(DWORD PPID, DWORD thisPID, std::vector<proc *> &processtree)
-{
-	int idx;
-
-	for (idx=0; idx < processtree.size(); idx++)
-	{
-		if (processtree[idx]->PID != thisPID &&  processtree[idx]->PPID  == PPID)
-		{
-			killProcessTreeRecursively(processtree[idx]->PID, thisPID, processtree);
-			//fprintf(stderr,"Found descendant =%d\n",processtree[idx]->PID );
-		}
-	}
-
-	killProcess(PPID);
-}
-
-int killProcessTree(DWORD PPID)
-{
-	HANDLE hSnapShot;
-	DWORD thisProcID=0;
-	BOOL ok;
-	PROCESSENTRY32 pe;
-	std::vector<proc *> processtree;
-
-	thisProcID = GetCurrentProcessId();
-
-	hSnapShot=CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
-
-	// Put all this process information into an array;
-	ok = Process32First(hSnapShot, &pe);
-	while (ok)
-	{
-		if ( pe.th32ProcessID != thisProcID)
-		{
-			proc *p = new proc;
-			p->PID = pe.th32ProcessID;
-			p->PPID = pe.th32ParentProcessID;
-			processtree.push_back(p);
-			//fprintf(stderr,"Found process =%d\n", pe.th32ProcessID );
-		}
-
-		ok = Process32Next(hSnapShot, &pe);
-	}
-
-	killProcessTreeRecursively(PPID, thisProcID, processtree);
-
-	CloseHandle(hSnapShot);
-
-	//fprintf(stderr,"Ending killproc\n", PPID);
-
-	return 0;
-}
-
-#endif
-
-void createDescrambleSemaphore(sbs_semaphore *s)
-{
-#ifdef WIN32
-	s->handle = CreateSemaphore(NULL, 1, 1, s->name);
-	if (s->handle)
-		CloseHandle(s->handle);
-	else
-		error("unable to create semaphore", s->name);
-#else
-	s->handle = sem_open(s->name, O_CREAT | O_EXCL, 0644, 1);
-
-  	if (s->handle == SEM_FAILED)
-	{
-		sem_close(s->handle);
-	  	error("unable to create semaphore", s->name);
-	}
-	sem_close(s->handle);
-#endif
-}
-
-void destroyDescrambleSemaphore(sbs_semaphore *s)
-{
-	#ifdef WIN32
-		/* can't destroy a windows semaphore... */
-	#else
-  		if (sem_unlink(s->name) != 0)
-		  	error("unable to unlink semaphore", s->name);
-	#endif
-}
-
-
-int waitForOutput(sbs_semaphore *s)
-{
-	/* try and open the semaphore now */
-        #ifdef WIN32
-		s->handle = CreateSemaphore(NULL, 1, 1, s->name);
-		if (!s->handle)
-			error("unable to open semaphore", s->name);
-        #else
-		s->handle = sem_open(s->name, 0);
-
-	  	if (s->handle == SEM_FAILED)
-		{
-    			sem_close(s->handle);
-      			error("unable to open semaphore", s->name);
-    		}
-	#endif
-
-    /* wait for the semaphore to be free [timeout after 60 seconds] */
- 	int timedOutFlag = 0;
-	#ifdef WIN32
- 		timedOutFlag = (WaitForSingleObject(s->handle, s->timeout) != WAIT_OBJECT_0);
-	#else
-		sem_wait(s->handle);
-	#endif
-
-	return timedOutFlag;
-}
-
-
-void  releaseOutput(sbs_semaphore *s)
-{
-	/* release the semaphore */
-	#ifdef WIN32
-		ReleaseSemaphore(s->handle, 1, NULL);
-	#else
-	   	sem_post(s->handle);
-	#endif
-
-	   /* clean up */
-	#ifdef WIN32
-		CloseHandle(s->handle);
-	#else
-	   	sem_close(s->handle);
-	#endif
-}
-
-void writeBuffers(int goodoutput)
-{
-	/* write stdin buffers to stdout. If the output comes
-	   from a partially-complete command then make sure that there
-	   is no malformed xml inside by escaping it. */
-	char *escaped_output=NULL;
-
-	#ifdef WIN32
-		DWORD dwWaitResult = WaitForSingleObject(
-		            bufferMutex,
-		            INFINITE);
-	#endif
-
-	for (int i = 0; i < buffers.size(); i++)
-	{
-		int bytes_out;
-		char *outbuf;
-
-		if (goodoutput != GOOD_OUTPUT)
-		{
-			if (!escaped_output)
-				escaped_output = new char[BufferSize*4];
-
-			if (!escaped_output)
-				error("No memory for escaped outputbuffer.",sem.name);
-
-			char *buf = buffers[i];
-			bytes_out = 0;
-			for (int idx=0; idx < bytesIn[i]; idx++)
-			{
-				switch (buf[idx])
-				{
-					case '&':
-						escaped_output[bytes_out++]='&';
-						escaped_output[bytes_out++]='a';
-						escaped_output[bytes_out++]='m';
-						escaped_output[bytes_out++]='p';
-						escaped_output[bytes_out++]=';';
-						break;
-					case '<':
-						escaped_output[bytes_out++]='&';
-						escaped_output[bytes_out++]='l';
-						escaped_output[bytes_out++]='t';
-						escaped_output[bytes_out++]=';';
-						break;
-					case '>':
-						escaped_output[bytes_out++]='&';
-						escaped_output[bytes_out++]='g';
-						escaped_output[bytes_out++]='t';
-						escaped_output[bytes_out++]=';';
-						break;
-					default:
-						if (!iscntrl(buf[idx]) || buf[idx] == '\n' || buf[idx] == '\r')
-							escaped_output[bytes_out++]=buf[idx];
-						break;
-				}
-
-			}
-
-			outbuf = escaped_output;
-
-		} else {
-			outbuf = buffers[i];
-			bytes_out = bytesIn[i];
-		}
-		fwrite(outbuf, 1, bytes_out, stdout);
-	}
-	#ifdef WIN32
-		ReleaseMutex(bufferMutex);
-	#endif
-
-	if (escaped_output)
-		delete escaped_output;
-	fflush(stdout);
-}
-
-#ifdef WIN32
-/*
- A Thread that kills this process if it is "stuck" in a read operation
- for longer than the timeout period.
-
- There are some race conditions here that don't matter. e.g. globalreadcounter
- is not protected.  This might result in an "unfair" timeout but we don't care
- because the timeout should be pretty long and anything that's even nearly
- a timeout deserves to be timed out.
-
- Additionally, if the timeout is so quick that this function starts before the first
- ever read has happened then there would be a premature timeout.  This is not likely
- so we also dont' care - the timeout has a minimum value which is more than long
- enough (500msec) to deal with that.
-
-*/
-DWORD descrambleKillerThread(void * param)
-{
-
-	sbs_semaphore *s;
-	unsigned int stored_globalreadcounter;
-	s = (sbs_semaphore *)param;
-
-	fflush(stderr);
-	//fprintf(stdout, " timeout=%u sem_name='%s' \n", s->timeout, s->name);
-
-	do
-	{
-		stored_globalreadcounter = globalreadcounter;
-		Sleep(s->timeout);
-	}
-	while (globalreadcounter != stored_globalreadcounter);
-
-	if (waitForOutput(s) != 0)
-	{
-		fprintf(stdout, "<descrambler reason='semaphore wait exceeded %ums timeout' semaphore='%s' />\n", s->timeout, s->name);
-		ExitProcess(3);
-	}
-
-	if (readstate)
-	{
-		fprintf(stdout, "<descrambler reason='command output read exceeded %ums timeout' semaphore='%s'>\n", s->timeout, s->name);
-		writeBuffers(BAD_OUTPUT);
-		fprintf(stdout, "</descrambler>\n");
-		fflush(stdout);
-		if (killPIDTree != 0)
-			killProcessTree(killPIDTree); // Make sure peers and parents all die. Nasty
-		ExitProcess(2);
-	}
-	else
-	{
-		writeBuffers(GOOD_OUTPUT);
-	}
-
-	// Don't release the semaphore in case the main thread
-	// gets it and tries to write the output.
-
-	// Input process finished while we were waiting
-	// for the semaphore so a false alarm.
-	fflush(stdout);
-	ExitProcess(0);
-}
-#endif
-
-
-int main(int argc, char *argv[])
-{
-	char usage[]="usage: %s [-t timeout_millisecs] [ -k kill_PID_tree_on_fail  ] buildID [start | stop]\nwhere timeout_millisecs >= 500\n";
-	int opt_res;
-	char options[]="t:k:";
-
-	sem.timeout = DEFAULT_TIMEOUT;
-
-
-	opt_res = getopt(argc, argv, options);
-
-	while (opt_res != -1 )
-	{
-		switch (opt_res)
-		{
-			case 'k':
-				if (!optarg)
-				{
-					fprintf(stderr, "PID argument required for 'kill PID tree on fail' option\n");
-					fprintf(stderr, usage, argv[0]);
-					exit(1);
-				}
-
-				killPIDTree = atol(optarg);
-				if (killPIDTree == 0)
-				{
-					fprintf(stderr, usage, argv[0]);
-					fprintf(stderr, "kill PID tree on fail must be > 0: %u\n", killPIDTree);
-					exit(1);
-				}
-				break;
-			case 't':
-				if (!optarg)
-				{
-					fprintf(stderr, "timeout argument required for timeout option\n");
-					fprintf(stderr, usage, argv[0]);
-					exit(1);
-				}
-
-				sem.timeout = atoi(optarg);
-				if (sem.timeout < 500)
-				{
-					fprintf(stderr, usage, argv[0]);
-					fprintf(stderr, "timeout was too low: %u\n", sem.timeout);
-					exit(1);
-				}
-				break;
-			case '?':
-			default:
-				fprintf(stderr, usage, argv[0]);
-				fprintf(stderr, "Unknown option. %s\n", opterr);
-				exit(1);
-				break;
-		}
-
-	opt_res = getopt(argc, argv, options);
-	}
-
-	if (optind >= argc)
-	{
-		fprintf(stderr, usage, argv[0]);
-		fprintf(stderr, "Missing buildID\n");
-		exit(1);
-	}
-
-	sem.name = argv[optind];
-
-	if (optind + 1 < argc)
-	{
-		optind++;
-
-		if (strncmp(argv[optind], "stop",4) == 0)
-			destroyDescrambleSemaphore(&sem);
-		else if (strncmp(argv[optind],"start",5) == 0)
-			createDescrambleSemaphore(&sem);
-		else
-		{
-			fprintf(stderr, usage, argv[0]);
-			fprintf(stderr, "Unknown argument:: %s\n", argv[optind]);
-			exit(1);
-		}
-
-		exit(0);
-	}
-
-	#ifdef WIN32
-
-		HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
-
-		bufferMutex = CreateMutex(NULL, FALSE, NULL);
-
-		/*
-		HANDLE WINAPI CreateThread(
-		  __in_opt   LPSECURITY_ATTRIBUTES lpThreadAttributes,
-		  __in       SIZE_T dwStackSize,
-		  __in       LPTHREAD_START_ROUTINE lpStartAddress,
-		  __in_opt   LPVOID lpParameter,
-		  __in       DWORD dwCreationFlags,
-		  __out_opt  LPDWORD lpThreadId
-		); */
-
-		DWORD killerThreadId;
-		HANDLE hKillerThread;
-
-		hKillerThread = CreateThread(NULL, 4096, (LPTHREAD_START_ROUTINE) descrambleKillerThread, (void*)&sem, 0, &killerThreadId);
-	#endif
-
-	/* read all of my stdin into buffers */
-	int bytesRead = 0;
-	int bufferIndex = 0;
-	do
-	{
-		char *buffer = new char[BufferSize];
-		if (buffer == NULL)
-			error("not enough memory for buffer", sem.name);
-
-
-		// Add an empty buffer in advance so that if there is a timeout
-		// the partial command result can be gathered.
-		#ifdef WIN32
-			DWORD dwWaitResult = WaitForSingleObject(
-			            bufferMutex,
-			            INFINITE);
-		#endif
-
-		buffers.push_back(buffer);
-		bytesIn.push_back(0);
-		int *counter = &bytesIn[bufferIndex];
-
-
-		#ifdef WIN32
-			ReleaseMutex(bufferMutex);
-		#endif
-		// Empty buffer added.
-
-		char c = fgetc(stdin);
-
-		//fprintf(stderr, "counter %d buffersize %d\n", *counter, BufferSize);
-		do
-		{
-			if (c == EOF)
-				break;
-			// escape unprintable characters that might make logs unparsable.
-			if (iscntrl(c) && !isspace(c))
-				c = '_';
-
-			buffer[*counter] = c;
-
-			*counter += 1;
-			if (*counter >= BufferSize)
-				break;
-
-			c = fgetc(stdin);
-			globalreadcounter = ++globalreadcounter % 65535*4;
-		}
-		while (c != EOF);
-
-		//fprintf(stderr, "## %d bytesin %d\n", bufferIndex, *counter);
-		bufferIndex++;
-	}
-	while (!feof(stdin) && !timeoutstate);
-	readstate = 0; //  Tell the killerthread that it can back off.
-
-	int timedout;
-
-	timedout = waitForOutput(&sem);
-
-
- 	if (timedout)
- 		error("timed out waiting for semaphore", sem.name);
- 	else
- 	{
-		writeBuffers(1);
-	}
-
-	releaseOutput(&sem);
-
- 	/* let the OS free the buffer memory */
-	exit(0);
-}
-
-
+/*
+* 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: 
+*
+*/
+
+
+/*
+ 	descramble.cpp:
+
+	Description
+	-----------
+	"descramble" is a program that buffers standard input until end of file
+	and then copies the buffers to the standard output in such a way that
+	if there are many copies of descramble running, each will be given an
+	opportunity to write the complete contents of its buffers while the
+	others wait.
+
+	Purpose
+	-------
+	descramble is used to ensure that output from multiple concurrent processes
+	is not interleaved.  It is useful in build systems such as GNU make with
+	the -j switch, although it requires that makefiles are changed before it can
+	work.
+
+	Design
+	------
+	This program may be built on Linux or on Windows.  On both platforms the
+	basic behavior is similar:
+		1) Read standard input into buffers.  Allocate these dynamically
+		   so that there is no limit.
+		2) Wait on a named or system-wide semaphore.
+		3) Output all the buffers to stdout.
+
+	The name of the semaphore is a parameter and should be chosen so that multiple
+	instances of the build system (or whatever process is running many tasks with
+	descramble) cannot block each other.
+
+
+	Special Considerations for Linux
+	--------------------------------
+	A named semaphore is a file in the filesystem.  It is not automatically removed
+	when a process exits.  descramble provides a "stop" parameter to be run at the
+	"end" of the build system (or other process) that will clean away this semaphore.
+
+
+	Special Considerations for Windows
+	----------------------------------
+	The windows implementation is built with the MINGW toolchain.  On windows
+	problems have been noticed that require a fairly complex timeout capability
+	such that descramble will not wait "forever" for output from stdin.
+	This solution currently uses a "kill thread" that will stop descramble if
+	it is blocked in a read on stdio for more than the timeout period.
+
+	The "kill thread" attempts to print as much of the input from stdin as has
+	been read so far.  It scans this for XML characters and escapes them, finally
+	printing its own XML-formatted error message with the escaped version of the
+	input between <descramble> tags.
+
+
+
+
+*/
+
+#include <stdio.h>
+#include <vector>
+#include <ctype.h>
+
+// what size chunks to allocate/read
+const int BufferSize = 4096;
+unsigned int globalreadcounter = 0;
+
+// OS specific headers
+#ifdef WIN32
+#include <windows.h>
+#include <tlhelp32.h>
+#include <fcntl.h> /*  _O_BINARY */
+#else
+#include <stdlib.h>
+#include <fcntl.h>
+#include <semaphore.h>
+#include <sys/types.h>
+#include <signal.h>
+#include <string.h>
+#endif
+#include <unistd.h>
+
+#define DEFAULT_TIMEOUT (600000) // 10 minutes
+
+#define GOOD_OUTPUT 1
+#define BAD_OUTPUT 0
+
+typedef struct
+{
+	char *name;
+	#ifdef WIN32
+ 		HANDLE handle;
+	#else
+		sem_t *handle;
+	#endif
+
+	unsigned int timeout;
+} sbs_semaphore;
+
+
+// readstate is a flag to indicate whether descramble is reading
+// it's standard input.
+// This allows the timeout thread on Windows to only cause the
+// process to exit if there is an overdue read operation on the
+// standard input.
+int readstate=1;
+int timeoutstate=0;
+
+// The output semaphore.
+sbs_semaphore sem;
+#ifdef WIN32
+	HANDLE bufferMutex;
+
+
+	// Make all output handling binary
+	unsigned int _CRT_fmode = _O_BINARY;
+
+
+	DWORD killPIDTree = 0;
+#else
+	pid_t killPIDTree = 0;
+#endif
+
+
+
+// Where we store all the standard input.
+std::vector<char*> buffers;
+std::vector<int> bytesIn;
+
+
+void error(const char *reason, char *SEM_NAME)
+{
+	fprintf(stderr, "<descrambler reason='%s' semaphore='%s' />\n", reason, SEM_NAME);
+	exit(1);
+}
+
+#ifdef WIN32
+
+void killProcess(DWORD pid)
+{
+	HANDLE proc = OpenProcess(PROCESS_TERMINATE,0,pid);
+	if (proc)
+	{
+		TerminateProcess(proc, 1);
+		//fprintf(stdout,"sent terminate to process=%d\n", pid);
+		CloseHandle(proc);
+	}
+	else
+	{
+		//fprintf(stderr,"Can't open process=%d\n", pid);
+	}
+}
+
+typedef struct {
+	DWORD PID;
+	DWORD PPID;
+} proc;
+
+void killProcessTreeRecursively(DWORD PPID, DWORD thisPID, std::vector<proc *> &processtree)
+{
+	int idx;
+
+	for (idx=0; idx < processtree.size(); idx++)
+	{
+		if (processtree[idx]->PID != thisPID &&  processtree[idx]->PPID  == PPID)
+		{
+			killProcessTreeRecursively(processtree[idx]->PID, thisPID, processtree);
+			//fprintf(stderr,"Found descendant =%d\n",processtree[idx]->PID );
+		}
+	}
+
+	killProcess(PPID);
+}
+
+int killProcessTree(DWORD PPID)
+{
+	HANDLE hSnapShot;
+	DWORD thisProcID=0;
+	BOOL ok;
+	PROCESSENTRY32 pe;
+	std::vector<proc *> processtree;
+
+	thisProcID = GetCurrentProcessId();
+
+	hSnapShot=CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
+
+	// Put all this process information into an array;
+	ok = Process32First(hSnapShot, &pe);
+	while (ok)
+	{
+		if ( pe.th32ProcessID != thisProcID)
+		{
+			proc *p = new proc;
+			p->PID = pe.th32ProcessID;
+			p->PPID = pe.th32ParentProcessID;
+			processtree.push_back(p);
+			//fprintf(stderr,"Found process =%d\n", pe.th32ProcessID );
+		}
+
+		ok = Process32Next(hSnapShot, &pe);
+	}
+
+	killProcessTreeRecursively(PPID, thisProcID, processtree);
+
+	CloseHandle(hSnapShot);
+
+	//fprintf(stderr,"Ending killproc\n", PPID);
+
+	return 0;
+}
+
+#endif
+
+void createDescrambleSemaphore(sbs_semaphore *s)
+{
+#ifdef WIN32
+	s->handle = CreateSemaphore(NULL, 1, 1, s->name);
+	if (s->handle)
+		CloseHandle(s->handle);
+	else
+		error("unable to create semaphore", s->name);
+#else
+	s->handle = sem_open(s->name, O_CREAT | O_EXCL, 0644, 1);
+
+  	if (s->handle == SEM_FAILED)
+	{
+		sem_close(s->handle);
+	  	error("unable to create semaphore", s->name);
+	}
+	sem_close(s->handle);
+#endif
+}
+
+void destroyDescrambleSemaphore(sbs_semaphore *s)
+{
+	#ifdef WIN32
+		/* can't destroy a windows semaphore... */
+	#else
+  		if (sem_unlink(s->name) != 0)
+		  	error("unable to unlink semaphore", s->name);
+	#endif
+}
+
+
+int waitForOutput(sbs_semaphore *s)
+{
+	/* try and open the semaphore now */
+        #ifdef WIN32
+		s->handle = CreateSemaphore(NULL, 1, 1, s->name);
+		if (!s->handle)
+			error("unable to open semaphore", s->name);
+        #else
+		s->handle = sem_open(s->name, 0);
+
+	  	if (s->handle == SEM_FAILED)
+		{
+    			sem_close(s->handle);
+      			error("unable to open semaphore", s->name);
+    		}
+	#endif
+
+    /* wait for the semaphore to be free [timeout after 60 seconds] */
+ 	int timedOutFlag = 0;
+	#ifdef WIN32
+ 		timedOutFlag = (WaitForSingleObject(s->handle, s->timeout) != WAIT_OBJECT_0);
+	#else
+		sem_wait(s->handle);
+	#endif
+
+	return timedOutFlag;
+}
+
+
+void  releaseOutput(sbs_semaphore *s)
+{
+	/* release the semaphore */
+	#ifdef WIN32
+		ReleaseSemaphore(s->handle, 1, NULL);
+	#else
+	   	sem_post(s->handle);
+	#endif
+
+	   /* clean up */
+	#ifdef WIN32
+		CloseHandle(s->handle);
+	#else
+	   	sem_close(s->handle);
+	#endif
+}
+
+void writeBuffers(int goodoutput)
+{
+	/* write stdin buffers to stdout. If the output comes
+	   from a partially-complete command then make sure that there
+	   is no malformed xml inside by escaping it. */
+	char *escaped_output=NULL;
+
+	#ifdef WIN32
+		DWORD dwWaitResult = WaitForSingleObject(
+		            bufferMutex,
+		            INFINITE);
+	#endif
+
+	for (int i = 0; i < buffers.size(); i++)
+	{
+		int bytes_out;
+		char *outbuf;
+
+		if (goodoutput != GOOD_OUTPUT)
+		{
+			if (!escaped_output)
+				escaped_output = new char[BufferSize*4];
+
+			if (!escaped_output)
+				error("No memory for escaped outputbuffer.",sem.name);
+
+			char *buf = buffers[i];
+			bytes_out = 0;
+			for (int idx=0; idx < bytesIn[i]; idx++)
+			{
+				switch (buf[idx])
+				{
+					case '&':
+						escaped_output[bytes_out++]='&';
+						escaped_output[bytes_out++]='a';
+						escaped_output[bytes_out++]='m';
+						escaped_output[bytes_out++]='p';
+						escaped_output[bytes_out++]=';';
+						break;
+					case '<':
+						escaped_output[bytes_out++]='&';
+						escaped_output[bytes_out++]='l';
+						escaped_output[bytes_out++]='t';
+						escaped_output[bytes_out++]=';';
+						break;
+					case '>':
+						escaped_output[bytes_out++]='&';
+						escaped_output[bytes_out++]='g';
+						escaped_output[bytes_out++]='t';
+						escaped_output[bytes_out++]=';';
+						break;
+					default:
+						if (!iscntrl(buf[idx]) || buf[idx] == '\n' || buf[idx] == '\r')
+							escaped_output[bytes_out++]=buf[idx];
+						break;
+				}
+
+			}
+
+			outbuf = escaped_output;
+
+		} else {
+			outbuf = buffers[i];
+			bytes_out = bytesIn[i];
+		}
+		fwrite(outbuf, 1, bytes_out, stdout);
+	}
+	#ifdef WIN32
+		ReleaseMutex(bufferMutex);
+	#endif
+
+	if (escaped_output)
+		delete escaped_output;
+	fflush(stdout);
+}
+
+#ifdef WIN32
+/*
+ A Thread that kills this process if it is "stuck" in a read operation
+ for longer than the timeout period.
+
+ There are some race conditions here that don't matter. e.g. globalreadcounter
+ is not protected.  This might result in an "unfair" timeout but we don't care
+ because the timeout should be pretty long and anything that's even nearly
+ a timeout deserves to be timed out.
+
+ Additionally, if the timeout is so quick that this function starts before the first
+ ever read has happened then there would be a premature timeout.  This is not likely
+ so we also dont' care - the timeout has a minimum value which is more than long
+ enough (500msec) to deal with that.
+
+*/
+DWORD descrambleKillerThread(void * param)
+{
+
+	sbs_semaphore *s;
+	unsigned int stored_globalreadcounter;
+	s = (sbs_semaphore *)param;
+
+	fflush(stderr);
+	//fprintf(stdout, " timeout=%u sem_name='%s' \n", s->timeout, s->name);
+
+	do
+	{
+		stored_globalreadcounter = globalreadcounter;
+		Sleep(s->timeout);
+	}
+	while (globalreadcounter != stored_globalreadcounter);
+
+	if (waitForOutput(s) != 0)
+	{
+		fprintf(stdout, "<descrambler reason='semaphore wait exceeded %ums timeout' semaphore='%s' />\n", s->timeout, s->name);
+		ExitProcess(3);
+	}
+
+	if (readstate)
+	{
+		fprintf(stdout, "<descrambler reason='command output read exceeded %ums timeout' semaphore='%s'>\n", s->timeout, s->name);
+		writeBuffers(BAD_OUTPUT);
+		fprintf(stdout, "</descrambler>\n");
+		fflush(stdout);
+		if (killPIDTree != 0)
+			killProcessTree(killPIDTree); // Make sure peers and parents all die. Nasty
+		ExitProcess(2);
+	}
+	else
+	{
+		writeBuffers(GOOD_OUTPUT);
+	}
+
+	// Don't release the semaphore in case the main thread
+	// gets it and tries to write the output.
+
+	// Input process finished while we were waiting
+	// for the semaphore so a false alarm.
+	fflush(stdout);
+	ExitProcess(0);
+}
+#endif
+
+
+int main(int argc, char *argv[])
+{
+	char usage[]="usage: %s [-t timeout_millisecs] [ -k kill_PID_tree_on_fail  ] buildID [start | stop]\nwhere timeout_millisecs >= 500\n";
+	int opt_res;
+	char options[]="t:k:";
+
+	sem.timeout = DEFAULT_TIMEOUT;
+
+
+	opt_res = getopt(argc, argv, options);
+
+	while (opt_res != -1 )
+	{
+		switch (opt_res)
+		{
+			case 'k':
+				if (!optarg)
+				{
+					fprintf(stderr, "PID argument required for 'kill PID tree on fail' option\n");
+					fprintf(stderr, usage, argv[0]);
+					exit(1);
+				}
+
+				killPIDTree = atol(optarg);
+				if (killPIDTree == 0)
+				{
+					fprintf(stderr, usage, argv[0]);
+					fprintf(stderr, "kill PID tree on fail must be > 0: %u\n", killPIDTree);
+					exit(1);
+				}
+				break;
+			case 't':
+				if (!optarg)
+				{
+					fprintf(stderr, "timeout argument required for timeout option\n");
+					fprintf(stderr, usage, argv[0]);
+					exit(1);
+				}
+
+				sem.timeout = atoi(optarg);
+				if (sem.timeout < 500)
+				{
+					fprintf(stderr, usage, argv[0]);
+					fprintf(stderr, "timeout was too low: %u\n", sem.timeout);
+					exit(1);
+				}
+				break;
+			case '?':
+			default:
+				fprintf(stderr, usage, argv[0]);
+				fprintf(stderr, "Unknown option. %s\n", opterr);
+				exit(1);
+				break;
+		}
+
+	opt_res = getopt(argc, argv, options);
+	}
+
+	if (optind >= argc)
+	{
+		fprintf(stderr, usage, argv[0]);
+		fprintf(stderr, "Missing buildID\n");
+		exit(1);
+	}
+
+	sem.name = argv[optind];
+
+	if (optind + 1 < argc)
+	{
+		optind++;
+
+		if (strncmp(argv[optind], "stop",4) == 0)
+			destroyDescrambleSemaphore(&sem);
+		else if (strncmp(argv[optind],"start",5) == 0)
+			createDescrambleSemaphore(&sem);
+		else
+		{
+			fprintf(stderr, usage, argv[0]);
+			fprintf(stderr, "Unknown argument:: %s\n", argv[optind]);
+			exit(1);
+		}
+
+		exit(0);
+	}
+
+	#ifdef WIN32
+
+		HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
+
+		bufferMutex = CreateMutex(NULL, FALSE, NULL);
+
+		/*
+		HANDLE WINAPI CreateThread(
+		  __in_opt   LPSECURITY_ATTRIBUTES lpThreadAttributes,
+		  __in       SIZE_T dwStackSize,
+		  __in       LPTHREAD_START_ROUTINE lpStartAddress,
+		  __in_opt   LPVOID lpParameter,
+		  __in       DWORD dwCreationFlags,
+		  __out_opt  LPDWORD lpThreadId
+		); */
+
+		DWORD killerThreadId;
+		HANDLE hKillerThread;
+
+		hKillerThread = CreateThread(NULL, 4096, (LPTHREAD_START_ROUTINE) descrambleKillerThread, (void*)&sem, 0, &killerThreadId);
+	#endif
+
+	/* read all of my stdin into buffers */
+	int bytesRead = 0;
+	int bufferIndex = 0;
+	do
+	{
+		char *buffer = new char[BufferSize];
+		if (buffer == NULL)
+			error("not enough memory for buffer", sem.name);
+
+
+		// Add an empty buffer in advance so that if there is a timeout
+		// the partial command result can be gathered.
+		#ifdef WIN32
+			DWORD dwWaitResult = WaitForSingleObject(
+			            bufferMutex,
+			            INFINITE);
+		#endif
+
+		buffers.push_back(buffer);
+		bytesIn.push_back(0);
+		int *counter = &bytesIn[bufferIndex];
+
+
+		#ifdef WIN32
+			ReleaseMutex(bufferMutex);
+		#endif
+		// Empty buffer added.
+
+		char c = fgetc(stdin);
+
+		//fprintf(stderr, "counter %d buffersize %d\n", *counter, BufferSize);
+		do
+		{
+			if (c == EOF)
+				break;
+			// escape unprintable characters that might make logs unparsable.
+			if (iscntrl(c) && !isspace(c))
+				c = '_';
+
+			buffer[*counter] = c;
+
+			*counter += 1;
+			if (*counter >= BufferSize)
+				break;
+
+			c = fgetc(stdin);
+			globalreadcounter = ++globalreadcounter % 65535*4;
+		}
+		while (c != EOF);
+
+		//fprintf(stderr, "## %d bytesin %d\n", bufferIndex, *counter);
+		bufferIndex++;
+	}
+	while (!feof(stdin) && !timeoutstate);
+	readstate = 0; //  Tell the killerthread that it can back off.
+
+	int timedout;
+
+	timedout = waitForOutput(&sem);
+
+
+ 	if (timedout)
+ 		error("timed out waiting for semaphore", sem.name);
+ 	else
+ 	{
+		writeBuffers(1);
+	}
+
+	releaseOutput(&sem);
+
+ 	/* let the OS free the buffer memory */
+	exit(0);
+}
+
+
--- a/sbsv2/raptor/util/dialog.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/dialog.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,50 +1,50 @@
-#
-# 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: 
-# Utility makefile 
-#
-
-
-# Build dialog for SBSv2 installer
-
-RAPTOR_DIALOG_VER:=1.1-20080819
-
-DIALOG_SOURCEDIR:=$(OUTPUTPATH)/dialog-$(RAPTOR_DIALOG_VER)
-DIALOG_TAR:=$(SBS_HOME)/util/ext/dialog-$(RAPTOR_DIALOG_VER).tar.gz
-
-
-define b_dialog
-
-.PHONY:: dialog
-
-all:: dialog
-
-dialog: $(INSTALLROOT)/bin/dialog
-	
-$(INSTALLROOT)/bin/dialog: $(DIALOG_TAR) 
-	rm -rf $(DIALOG_SOURCEDIR) && \
-	cd $(OUTPUTPATH) && \
-	tar -xzf $(DIALOG_TAR) && \
-	(  \
-	cd $(DIALOG_SOURCEDIR) && \
-	CFLAGS="-O3 $(GCCTUNE) -s" ./configure --prefix=$(INSTALLROOT) && \
-	$(MAKE) -j8 && $(MAKE) install \
-	)
-endef
-
-$(eval $(b_dialog))
-
-
-
-
+#
+# 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: 
+# Utility makefile 
+#
+
+
+# Build dialog for SBSv2 installer
+
+RAPTOR_DIALOG_VER:=1.1-20080819
+
+DIALOG_SOURCEDIR:=$(OUTPUTPATH)/dialog-$(RAPTOR_DIALOG_VER)
+DIALOG_TAR:=$(SBS_HOME)/util/ext/dialog-$(RAPTOR_DIALOG_VER).tar.gz
+
+
+define b_dialog
+
+.PHONY:: dialog
+
+all:: dialog
+
+dialog: $(INSTALLROOT)/bin/dialog
+	
+$(INSTALLROOT)/bin/dialog: $(DIALOG_TAR) 
+	rm -rf $(DIALOG_SOURCEDIR) && \
+	cd $(OUTPUTPATH) && \
+	tar -xzf $(DIALOG_TAR) && \
+	(  \
+	cd $(DIALOG_SOURCEDIR) && \
+	CFLAGS="-O3 $(GCCTUNE) -s" ./configure --prefix=$(INSTALLROOT) && \
+	$(MAKE) -j8 && $(MAKE) install \
+	)
+endef
+
+$(eval $(b_dialog))
+
+
+
+
--- a/sbsv2/raptor/util/gccprogram.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/gccprogram.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,72 +1,72 @@
-#
-# 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: 
-# Utility makefile 
-#
-
-define cpp2obj
-OBJECTFILE:=$(OUTPUTPATH)/$(TARGET)/$(notdir $(SOURCEFILE:.cpp=.o))
-$$(OBJECTFILE): $(SOURCEFILE)
-	g++ $(HOSTMACROS) $(CFLAGS) -c $(SOURCEFILE) -o $$@
-	
-OBJECTS:=$$(OBJECTS) $$(OBJECTFILE)
-
-endef 
-
-define cppprogram
-
-all:: $(BINDIR)/$(TARGET)$(PROGRAMEXT)
-
-$(foreach SOURCEFILE,$(SOURCES),$(cpp2obj))
-
-$(BINDIR)/$(TARGET)$(PROGRAMEXT): $$(OBJECTS)
-	g++ $(LDFLAGS) $$^ -o $$@
-	
-$$(shell mkdir -p $(OUTPUTPATH)/$(TARGET) $(BINDIR))
-
-CLEANFILES:=$$(OBJECTS)
-$(cleanlog)
-
-endef
-
-define c2obj
-OBJECTFILE:=$(OUTPUTPATH)/$(TARGET)/$(notdir $(SOURCEFILE:.c=.o))
-$$(OBJECTFILE): $(SOURCEFILE)
-	gcc $(HOSTMACROS) $(CFLAGS) -c $(SOURCEFILE) -o $$@
-	
-OBJECTS:=$$(OBJECTS) $$(OBJECTFILE)
-
-endef 
-
-
-define cprogram
-
-OBJECTS:=
-
-all:: $(BINDIR)/$(TARGET)$(PROGRAMEXT)
-	
-.PHONY:: $(TARGET)
-$(TARGET):: $(BINDIR)/$(TARGET)$(PROGRAMEXT)
-
-$(foreach SOURCEFILE,$(SOURCES),$(c2obj))
-
-$(BINDIR)/$(TARGET)$(PROGRAMEXT): $$(OBJECTS)
-	gcc $(LDFLAGS) $$^ -o $$@
-	
-$$(shell mkdir -p $(OUTPUTPATH)/$(TARGET))
-
-CLEANFILES:=$$(OBJECTS)
-$(cleanlog)
-
-endef
+#
+# 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: 
+# Utility makefile 
+#
+
+define cpp2obj
+OBJECTFILE:=$(OUTPUTPATH)/$(TARGET)/$(notdir $(SOURCEFILE:.cpp=.o))
+$$(OBJECTFILE): $(SOURCEFILE)
+	g++ $(HOSTMACROS) $(CFLAGS) -c $(SOURCEFILE) -o $$@
+	
+OBJECTS:=$$(OBJECTS) $$(OBJECTFILE)
+
+endef 
+
+define cppprogram
+
+all:: $(BINDIR)/$(TARGET)$(PROGRAMEXT)
+
+$(foreach SOURCEFILE,$(SOURCES),$(cpp2obj))
+
+$(BINDIR)/$(TARGET)$(PROGRAMEXT): $$(OBJECTS)
+	g++ $(LDFLAGS) $$^ -o $$@
+	
+$$(shell mkdir -p $(OUTPUTPATH)/$(TARGET) $(BINDIR))
+
+CLEANFILES:=$$(OBJECTS)
+$(cleanlog)
+
+endef
+
+define c2obj
+OBJECTFILE:=$(OUTPUTPATH)/$(TARGET)/$(notdir $(SOURCEFILE:.c=.o))
+$$(OBJECTFILE): $(SOURCEFILE)
+	gcc $(HOSTMACROS) $(CFLAGS) -c $(SOURCEFILE) -o $$@
+	
+OBJECTS:=$$(OBJECTS) $$(OBJECTFILE)
+
+endef 
+
+
+define cprogram
+
+OBJECTS:=
+
+all:: $(BINDIR)/$(TARGET)$(PROGRAMEXT)
+	
+.PHONY:: $(TARGET)
+$(TARGET):: $(BINDIR)/$(TARGET)$(PROGRAMEXT)
+
+$(foreach SOURCEFILE,$(SOURCES),$(c2obj))
+
+$(BINDIR)/$(TARGET)$(PROGRAMEXT): $$(OBJECTS)
+	gcc  $$^ $(LDFLAGS) -o $$@
+	
+$$(shell mkdir -p $(OUTPUTPATH)/$(TARGET))
+
+CLEANFILES:=$$(OBJECTS)
+$(cleanlog)
+
+endef
--- a/sbsv2/raptor/util/gccxml.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/gccxml.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,39 +1,39 @@
-#
-# 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: 
-# Utility makefile 
-#
-
-GCCXML_TAR:=$(SBS_HOME)/util/ext/gccxml.tar.gz
-
-
-define b_gccxml
-
-.PHONY:: gccxml
-
-all:: gccxml
-
-gccxml: $(INSTALLROOT)/bin/gccxml_cc1plus
-	
-$(INSTALLROOT)/bin/gccxml_cc1plus: $(GCCXML_TAR)
-	cd $(INSTALLROOT) && \
-	tar -xzf $(GCCXML_TAR) 
-
-endef
-
-$(eval $(b_gccxml))
-
-
-
-
+#
+# 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: 
+# Utility makefile 
+#
+
+GCCXML_TAR:=$(SBS_HOME)/util/ext/gccxml.tar.gz
+
+
+define b_gccxml
+
+.PHONY:: gccxml
+
+all:: gccxml
+
+gccxml: $(INSTALLROOT)/bin/gccxml_cc1plus
+	
+$(INSTALLROOT)/bin/gccxml_cc1plus: $(GCCXML_TAR)
+	cd $(INSTALLROOT) && \
+	tar -xzf $(GCCXML_TAR) 
+
+endef
+
+$(eval $(b_gccxml))
+
+
+
+
--- a/sbsv2/raptor/util/install-linux/makeself-header.sh	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/install-linux/makeself-header.sh	Wed Jun 23 16:56:47 2010 +0800
@@ -1,401 +1,401 @@
-cat << EOF  > "$archname"
-#!/bin/sh
-# This script was generated using Makeself $MS_VERSION
-
-CRCsum="$CRCsum"
-MD5="$MD5sum"
-TMPROOT=\${TMPDIR:=/tmp}
-
-label="$LABEL"
-script="$SCRIPT"
-scriptargs="$SCRIPTARGS"
-targetdir="$archdirname"
-filesizes="$filesizes"
-keep=$KEEP
-
-print_cmd_arg=""
-if type printf > /dev/null; then
-    print_cmd="printf"
-elif test -x /usr/ucb/echo; then
-    print_cmd="/usr/ucb/echo"
-else
-    print_cmd="echo"
-fi
-
-unset CDPATH
-
-MS_Printf()
-{
-    \$print_cmd \$print_cmd_arg "\$1"
-}
-
-MS_Progress()
-{
-    while read a; do
-	MS_Printf .
-    done
-}
-
-MS_diskspace()
-{
-	(
-	if test -d /usr/xpg4/bin; then
-		PATH=/usr/xpg4/bin:\$PATH
-	fi
-	df -kP "\$1" | tail -1 | awk '{print \$4}'
-	)
-}
-
-MS_dd()
-{
-    blocks=\`expr \$3 / 1024\`
-    bytes=\`expr \$3 % 1024\`
-    dd if="\$1" ibs=\$2 skip=1 obs=1024 conv=sync 2> /dev/null | \\
-    { test \$blocks -gt 0 && dd ibs=1024 obs=1024 count=\$blocks ; \\
-      test \$bytes  -gt 0 && dd ibs=1 obs=1024 count=\$bytes ; } 2> /dev/null
-}
-
-MS_Help()
-{
-    cat << EOH >&2
-Makeself version $MS_VERSION
- 1) Getting help or info about \$0 :
-  \$0 --help   Print this message
-  \$0 --info   Print embedded info : title, default target directory, embedded script ...
-  \$0 --lsm    Print embedded lsm entry (or no LSM)
-  \$0 --list   Print the list of files in the archive
-  \$0 --check  Checks integrity of the archive
- 
- 2) Running \$0 :
-  \$0 [options] [--] [additional arguments to embedded script]
-  with following options (in that order)
-  --confirm             Ask before running embedded script
-  --noexec              Do not run embedded script
-  --keep                Do not erase target directory after running
-			the embedded script
-  --nox11               Do not spawn an xterm
-  --nochown             Do not give the extracted files to the current user
-  --target NewDirectory Extract in NewDirectory
-  --tar arg1 [arg2 ...] Access the contents of the archive through the tar command
-  --                    Following arguments will be passed to the embedded script
-EOH
-}
-
-MS_Check()
-{
-    OLD_PATH="\$PATH"
-    PATH=\${GUESS_MD5_PATH:-"\$OLD_PATH:/bin:/usr/bin:/sbin:/usr/local/ssl/bin:/usr/local/bin:/opt/openssl/bin"}
-	MD5_ARG=""
-    MD5_PATH=\`exec <&- 2>&-; which md5sum || type md5sum\`
-    test -x "\$MD5_PATH" || MD5_PATH=\`exec <&- 2>&-; which md5 || type md5\`
-	test -x "\$MD5_PATH" || MD5_PATH=\`exec <&- 2>&-; which digest || type digest\`
-    PATH="\$OLD_PATH"
-
-    MS_Printf "Verifying archive integrity..."
-    offset=\`head -n $SKIP "\$1" | wc -c | tr -d " "\`
-    verb=\$2
-    i=1
-    for s in \$filesizes
-    do
-		crc=\`echo \$CRCsum | cut -d" " -f\$i\`
-		if test -x "\$MD5_PATH"; then
-			if test \`basename \$MD5_PATH\` = digest; then
-				MD5_ARG="-a md5"
-			fi
-			md5=\`echo \$MD5 | cut -d" " -f\$i\`
-			if test \$md5 = "00000000000000000000000000000000"; then
-				test x\$verb = xy && echo " \$1 does not contain an embedded MD5 checksum." >&2
-			else
-				md5sum=\`MS_dd "\$1" \$offset \$s | eval "\$MD5_PATH \$MD5_ARG" | cut -b-32\`;
-				if test "\$md5sum" != "\$md5"; then
-					echo "Error in MD5 checksums: \$md5sum is different from \$md5" >&2
-					exit 2
-				else
-					test x\$verb = xy && MS_Printf " MD5 checksums are OK." >&2
-				fi
-				crc="0000000000"; verb=n
-			fi
-		fi
-		if test \$crc = "0000000000"; then
-			test x\$verb = xy && echo " \$1 does not contain a CRC checksum." >&2
-		else
-			sum1=\`MS_dd "\$1" \$offset \$s | CMD_ENV=xpg4 cksum | awk '{print \$1}'\`
-			if test "\$sum1" = "\$crc"; then
-				test x\$verb = xy && MS_Printf " CRC checksums are OK." >&2
-			else
-				echo "Error in checksums: \$sum1 is different from \$crc"
-				exit 2;
-			fi
-		fi
-		i=\`expr \$i + 1\`
-		offset=\`expr \$offset + \$s\`
-    done
-    echo " All good."
-}
-
-UnTAR()
-{
-    tar \$1vf - 2>&1 || { echo Extraction failed. > /dev/tty; kill -15 \$$; }
-}
-
-finish=true
-xterm_loop=
-nox11=$NOX11
-copy=$COPY
-ownership=y
-verbose=n
-
-initargs="\$@"
-
-while true
-do
-    case "\$1" in
-    -h | --help)
-	MS_Help
-	exit 0
-	;;
-    --info)
-	echo Identification: "\$label"
-	echo Target directory: "\$targetdir"
-	echo Uncompressed size: $USIZE KB
-	echo Compression: $COMPRESS
-	echo Date of packaging: $DATE
-	echo Built with Makeself version $MS_VERSION on $OSTYPE
-	echo Build command was: "$MS_COMMAND"
-	if test x\$script != x; then
-	    echo Script run after extraction:
-	    echo "    " \$script \$scriptargs
-	fi
-	if test x"$copy" = xcopy; then
-		echo "Archive will copy itself to a temporary location"
-	fi
-	if test x"$KEEP" = xy; then
-	    echo "directory \$targetdir is permanent"
-	else
-	    echo "\$targetdir will be removed after extraction"
-	fi
-	exit 0
-	;;
-    --dumpconf)
-	echo LABEL=\"\$label\"
-	echo SCRIPT=\"\$script\"
-	echo SCRIPTARGS=\"\$scriptargs\"
-	echo archdirname=\"$archdirname\"
-	echo KEEP=$KEEP
-	echo COMPRESS=$COMPRESS
-	echo filesizes=\"\$filesizes\"
-	echo CRCsum=\"\$CRCsum\"
-	echo MD5sum=\"\$MD5\"
-	echo OLDUSIZE=$USIZE
-	echo OLDSKIP=`expr $SKIP + 1`
-	exit 0
-	;;
-    --lsm)
-cat << EOLSM
-EOF
-eval "$LSM_CMD"
-cat << EOF  >> "$archname"
-EOLSM
-	exit 0
-	;;
-    --list)
-	echo Target directory: \$targetdir
-	offset=\`head -n $SKIP "\$0" | wc -c | tr -d " "\`
-	for s in \$filesizes
-	do
-	    MS_dd "\$0" \$offset \$s | eval "$GUNZIP_CMD" | UnTAR t
-	    offset=\`expr \$offset + \$s\`
-	done
-	exit 0
-	;;
-	--tar)
-	offset=\`head -n $SKIP "\$0" | wc -c | tr -d " "\`
-	arg1="\$2"
-	shift 2
-	for s in \$filesizes
-	do
-	    MS_dd "\$0" \$offset \$s | eval "$GUNZIP_CMD" | tar "\$arg1" - \$*
-	    offset=\`expr \$offset + \$s\`
-	done
-	exit 0
-	;;
-    --check)
-	MS_Check "\$0" y
-	exit 0
-	;;
-    --confirm)
-	verbose=y
-	shift
-	;;
-	--noexec)
-	script=""
-	shift
-	;;
-    --keep)
-	keep=y
-	shift
-	;;
-    --target)
-	keep=y
-	targetdir=\${2:-.}
-	shift 2
-	;;
-    --nox11)
-	nox11=y
-	shift
-	;;
-    --nochown)
-	ownership=n
-	shift
-	;;
-    --xwin)
-	finish="echo Press Return to close this window...; read junk"
-	xterm_loop=1
-	shift
-	;;
-    --phase2)
-	copy=phase2
-	shift
-	;;
-    --)
-	shift
-	break ;;
-    -*)
-	echo Unrecognized flag : "\$1" >&2
-	MS_Help
-	exit 1
-	;;
-    *)
-	break ;;
-    esac
-done
-
-case "\$copy" in
-copy)
-    tmpdir=\$TMPROOT/makeself.\$RANDOM.\`date +"%y%m%d%H%M%S"\`.\$\$
-    mkdir "\$tmpdir" || {
-	echo "Could not create temporary directory \$tmpdir" >&2
-	exit 1
-    }
-    SCRIPT_COPY="\$tmpdir/makeself"
-    echo "Copying to a temporary location..." >&2
-    cp "\$0" "\$SCRIPT_COPY"
-    chmod +x "\$SCRIPT_COPY"
-    cd "\$TMPROOT"
-    exec "\$SCRIPT_COPY" --phase2 -- \$initargs
-    ;;
-phase2)
-    finish="\$finish ; rm -rf \`dirname \$0\`"
-    ;;
-esac
-
-if test "\$nox11" = "n"; then
-    if tty -s; then                 # Do we have a terminal?
-	:
-    else
-        if test x"\$DISPLAY" != x -a x"\$xterm_loop" = x; then  # No, but do we have X?
-            if xset q > /dev/null 2>&1; then # Check for valid DISPLAY variable
-                GUESS_XTERMS="xterm rxvt dtterm eterm Eterm kvt konsole aterm"
-                for a in \$GUESS_XTERMS; do
-                    if type \$a >/dev/null 2>&1; then
-                        XTERM=\$a
-                        break
-                    fi
-                done
-                chmod a+x \$0 || echo Please add execution rights on \$0
-                if test \`echo "\$0" | cut -c1\` = "/"; then # Spawn a terminal!
-                    exec \$XTERM -title "\$label" -e "\$0" --xwin "\$initargs"
-                else
-                    exec \$XTERM -title "\$label" -e "./\$0" --xwin "\$initargs"
-                fi
-            fi
-        fi
-    fi
-fi
-
-if test "\$targetdir" = "."; then
-    tmpdir="."
-else
-    if test "\$keep" = y; then
-	echo "Creating directory \$targetdir" >&2
-	tmpdir="\$targetdir"
-	dashp="-p"
-    else
-	tmpdir="\$TMPROOT/selfgz\$\$\$RANDOM"
-	dashp=""
-    fi
-    mkdir \$dashp \$tmpdir || {
-	echo 'Cannot create target directory' \$tmpdir >&2
-	echo 'You should try option --target OtherDirectory' >&2
-	eval \$finish
-	exit 1
-    }
-fi
-
-location="\`pwd\`"
-if test x\$SETUP_NOCHECK != x1; then
-    MS_Check "\$0"
-fi
-offset=\`head -n $SKIP "\$0" | wc -c | tr -d " "\`
-
-if test x"\$verbose" = xy; then
-	MS_Printf "About to extract $USIZE KB in \$tmpdir ... Proceed ? [Y/n] "
-	read yn
-	if test x"\$yn" = xn; then
-		eval \$finish; exit 1
-	fi
-fi
-
-MS_Printf "Uncompressing \$label"
-res=3
-if test "\$keep" = n; then
-    trap 'echo Signal caught, cleaning up >&2; cd \$TMPROOT; /bin/rm -rf \$tmpdir; eval \$finish; exit 15' 1 2 3 15
-fi
-
-leftspace=\`MS_diskspace \$tmpdir\`
-if test \$leftspace -lt $USIZE; then
-    echo
-    echo "Not enough space left in "\`dirname \$tmpdir\`" (\$leftspace KB) to decompress \$0 ($USIZE KB)" >&2
-    if test "\$keep" = n; then
-        echo "Consider setting TMPDIR to a directory with more free space."
-   fi
-    eval \$finish; exit 1
-fi
-
-for s in \$filesizes
-do
-    if MS_dd "\$0" \$offset \$s | eval "$GUNZIP_CMD" | ( cd "\$tmpdir"; UnTAR x ) | MS_Progress; then
-		if test x"\$ownership" = xy; then
-			(PATH=/usr/xpg4/bin:\$PATH; cd "\$tmpdir"; chown -R \`id -u\` .;  chgrp -R \`id -g\` .)
-		fi
-    else
-		echo
-		echo "Unable to decompress \$0" >&2
-		eval \$finish; exit 1
-    fi
-    offset=\`expr \$offset + \$s\`
-done
-echo
-
-cd "\$tmpdir"
-res=0
-if test x"\$script" != x; then
-    if test x"\$verbose" = xy; then
-		MS_Printf "OK to execute: \$script \$scriptargs \$* ? [Y/n] "
-		read yn
-		if test x"\$yn" = x -o x"\$yn" = xy -o x"\$yn" = xY; then
-			eval \$script \$scriptargs \$*; res=\$?;
-		fi
-    else
-		eval \$script \$scriptargs \$*; res=\$?
-    fi
-    if test \$res -ne 0; then
-		test x"\$verbose" = xy && echo "The program '\$script' returned an error code (\$res)" >&2
-    fi
-fi
-if test "\$keep" = n; then
-    cd \$TMPROOT
-    /bin/rm -rf \$tmpdir
-fi
-eval \$finish; exit \$res
-EOF
+cat << EOF  > "$archname"
+#!/bin/sh
+# This script was generated using Makeself $MS_VERSION
+
+CRCsum="$CRCsum"
+MD5="$MD5sum"
+TMPROOT=\${TMPDIR:=/tmp}
+
+label="$LABEL"
+script="$SCRIPT"
+scriptargs="$SCRIPTARGS"
+targetdir="$archdirname"
+filesizes="$filesizes"
+keep=$KEEP
+
+print_cmd_arg=""
+if type printf > /dev/null; then
+    print_cmd="printf"
+elif test -x /usr/ucb/echo; then
+    print_cmd="/usr/ucb/echo"
+else
+    print_cmd="echo"
+fi
+
+unset CDPATH
+
+MS_Printf()
+{
+    \$print_cmd \$print_cmd_arg "\$1"
+}
+
+MS_Progress()
+{
+    while read a; do
+	MS_Printf .
+    done
+}
+
+MS_diskspace()
+{
+	(
+	if test -d /usr/xpg4/bin; then
+		PATH=/usr/xpg4/bin:\$PATH
+	fi
+	df -kP "\$1" | tail -1 | awk '{print \$4}'
+	)
+}
+
+MS_dd()
+{
+    blocks=\`expr \$3 / 1024\`
+    bytes=\`expr \$3 % 1024\`
+    dd if="\$1" ibs=\$2 skip=1 obs=1024 conv=sync 2> /dev/null | \\
+    { test \$blocks -gt 0 && dd ibs=1024 obs=1024 count=\$blocks ; \\
+      test \$bytes  -gt 0 && dd ibs=1 obs=1024 count=\$bytes ; } 2> /dev/null
+}
+
+MS_Help()
+{
+    cat << EOH >&2
+Makeself version $MS_VERSION
+ 1) Getting help or info about \$0 :
+  \$0 --help   Print this message
+  \$0 --info   Print embedded info : title, default target directory, embedded script ...
+  \$0 --lsm    Print embedded lsm entry (or no LSM)
+  \$0 --list   Print the list of files in the archive
+  \$0 --check  Checks integrity of the archive
+ 
+ 2) Running \$0 :
+  \$0 [options] [--] [additional arguments to embedded script]
+  with following options (in that order)
+  --confirm             Ask before running embedded script
+  --noexec              Do not run embedded script
+  --keep                Do not erase target directory after running
+			the embedded script
+  --nox11               Do not spawn an xterm
+  --nochown             Do not give the extracted files to the current user
+  --target NewDirectory Extract in NewDirectory
+  --tar arg1 [arg2 ...] Access the contents of the archive through the tar command
+  --                    Following arguments will be passed to the embedded script
+EOH
+}
+
+MS_Check()
+{
+    OLD_PATH="\$PATH"
+    PATH=\${GUESS_MD5_PATH:-"\$OLD_PATH:/bin:/usr/bin:/sbin:/usr/local/ssl/bin:/usr/local/bin:/opt/openssl/bin"}
+	MD5_ARG=""
+    MD5_PATH=\`exec <&- 2>&-; which md5sum || type md5sum\`
+    test -x "\$MD5_PATH" || MD5_PATH=\`exec <&- 2>&-; which md5 || type md5\`
+	test -x "\$MD5_PATH" || MD5_PATH=\`exec <&- 2>&-; which digest || type digest\`
+    PATH="\$OLD_PATH"
+
+    MS_Printf "Verifying archive integrity..."
+    offset=\`head -n $SKIP "\$1" | wc -c | tr -d " "\`
+    verb=\$2
+    i=1
+    for s in \$filesizes
+    do
+		crc=\`echo \$CRCsum | cut -d" " -f\$i\`
+		if test -x "\$MD5_PATH"; then
+			if test \`basename \$MD5_PATH\` = digest; then
+				MD5_ARG="-a md5"
+			fi
+			md5=\`echo \$MD5 | cut -d" " -f\$i\`
+			if test \$md5 = "00000000000000000000000000000000"; then
+				test x\$verb = xy && echo " \$1 does not contain an embedded MD5 checksum." >&2
+			else
+				md5sum=\`MS_dd "\$1" \$offset \$s | eval "\$MD5_PATH \$MD5_ARG" | cut -b-32\`;
+				if test "\$md5sum" != "\$md5"; then
+					echo "Error in MD5 checksums: \$md5sum is different from \$md5" >&2
+					exit 2
+				else
+					test x\$verb = xy && MS_Printf " MD5 checksums are OK." >&2
+				fi
+				crc="0000000000"; verb=n
+			fi
+		fi
+		if test \$crc = "0000000000"; then
+			test x\$verb = xy && echo " \$1 does not contain a CRC checksum." >&2
+		else
+			sum1=\`MS_dd "\$1" \$offset \$s | CMD_ENV=xpg4 cksum | awk '{print \$1}'\`
+			if test "\$sum1" = "\$crc"; then
+				test x\$verb = xy && MS_Printf " CRC checksums are OK." >&2
+			else
+				echo "Error in checksums: \$sum1 is different from \$crc"
+				exit 2;
+			fi
+		fi
+		i=\`expr \$i + 1\`
+		offset=\`expr \$offset + \$s\`
+    done
+    echo " All good."
+}
+
+UnTAR()
+{
+    tar \$1vf - 2>&1 || { echo Extraction failed. > /dev/tty; kill -15 \$$; }
+}
+
+finish=true
+xterm_loop=
+nox11=$NOX11
+copy=$COPY
+ownership=y
+verbose=n
+
+initargs="\$@"
+
+while true
+do
+    case "\$1" in
+    -h | --help)
+	MS_Help
+	exit 0
+	;;
+    --info)
+	echo Identification: "\$label"
+	echo Target directory: "\$targetdir"
+	echo Uncompressed size: $USIZE KB
+	echo Compression: $COMPRESS
+	echo Date of packaging: $DATE
+	echo Built with Makeself version $MS_VERSION on $OSTYPE
+	echo Build command was: "$MS_COMMAND"
+	if test x\$script != x; then
+	    echo Script run after extraction:
+	    echo "    " \$script \$scriptargs
+	fi
+	if test x"$copy" = xcopy; then
+		echo "Archive will copy itself to a temporary location"
+	fi
+	if test x"$KEEP" = xy; then
+	    echo "directory \$targetdir is permanent"
+	else
+	    echo "\$targetdir will be removed after extraction"
+	fi
+	exit 0
+	;;
+    --dumpconf)
+	echo LABEL=\"\$label\"
+	echo SCRIPT=\"\$script\"
+	echo SCRIPTARGS=\"\$scriptargs\"
+	echo archdirname=\"$archdirname\"
+	echo KEEP=$KEEP
+	echo COMPRESS=$COMPRESS
+	echo filesizes=\"\$filesizes\"
+	echo CRCsum=\"\$CRCsum\"
+	echo MD5sum=\"\$MD5\"
+	echo OLDUSIZE=$USIZE
+	echo OLDSKIP=`expr $SKIP + 1`
+	exit 0
+	;;
+    --lsm)
+cat << EOLSM
+EOF
+eval "$LSM_CMD"
+cat << EOF  >> "$archname"
+EOLSM
+	exit 0
+	;;
+    --list)
+	echo Target directory: \$targetdir
+	offset=\`head -n $SKIP "\$0" | wc -c | tr -d " "\`
+	for s in \$filesizes
+	do
+	    MS_dd "\$0" \$offset \$s | eval "$GUNZIP_CMD" | UnTAR t
+	    offset=\`expr \$offset + \$s\`
+	done
+	exit 0
+	;;
+	--tar)
+	offset=\`head -n $SKIP "\$0" | wc -c | tr -d " "\`
+	arg1="\$2"
+	shift 2
+	for s in \$filesizes
+	do
+	    MS_dd "\$0" \$offset \$s | eval "$GUNZIP_CMD" | tar "\$arg1" - \$*
+	    offset=\`expr \$offset + \$s\`
+	done
+	exit 0
+	;;
+    --check)
+	MS_Check "\$0" y
+	exit 0
+	;;
+    --confirm)
+	verbose=y
+	shift
+	;;
+	--noexec)
+	script=""
+	shift
+	;;
+    --keep)
+	keep=y
+	shift
+	;;
+    --target)
+	keep=y
+	targetdir=\${2:-.}
+	shift 2
+	;;
+    --nox11)
+	nox11=y
+	shift
+	;;
+    --nochown)
+	ownership=n
+	shift
+	;;
+    --xwin)
+	finish="echo Press Return to close this window...; read junk"
+	xterm_loop=1
+	shift
+	;;
+    --phase2)
+	copy=phase2
+	shift
+	;;
+    --)
+	shift
+	break ;;
+    -*)
+	echo Unrecognized flag : "\$1" >&2
+	MS_Help
+	exit 1
+	;;
+    *)
+	break ;;
+    esac
+done
+
+case "\$copy" in
+copy)
+    tmpdir=\$TMPROOT/makeself.\$RANDOM.\`date +"%y%m%d%H%M%S"\`.\$\$
+    mkdir "\$tmpdir" || {
+	echo "Could not create temporary directory \$tmpdir" >&2
+	exit 1
+    }
+    SCRIPT_COPY="\$tmpdir/makeself"
+    echo "Copying to a temporary location..." >&2
+    cp "\$0" "\$SCRIPT_COPY"
+    chmod +x "\$SCRIPT_COPY"
+    cd "\$TMPROOT"
+    exec "\$SCRIPT_COPY" --phase2 -- \$initargs
+    ;;
+phase2)
+    finish="\$finish ; rm -rf \`dirname \$0\`"
+    ;;
+esac
+
+if test "\$nox11" = "n"; then
+    if tty -s; then                 # Do we have a terminal?
+	:
+    else
+        if test x"\$DISPLAY" != x -a x"\$xterm_loop" = x; then  # No, but do we have X?
+            if xset q > /dev/null 2>&1; then # Check for valid DISPLAY variable
+                GUESS_XTERMS="xterm rxvt dtterm eterm Eterm kvt konsole aterm"
+                for a in \$GUESS_XTERMS; do
+                    if type \$a >/dev/null 2>&1; then
+                        XTERM=\$a
+                        break
+                    fi
+                done
+                chmod a+x \$0 || echo Please add execution rights on \$0
+                if test \`echo "\$0" | cut -c1\` = "/"; then # Spawn a terminal!
+                    exec \$XTERM -title "\$label" -e "\$0" --xwin "\$initargs"
+                else
+                    exec \$XTERM -title "\$label" -e "./\$0" --xwin "\$initargs"
+                fi
+            fi
+        fi
+    fi
+fi
+
+if test "\$targetdir" = "."; then
+    tmpdir="."
+else
+    if test "\$keep" = y; then
+	echo "Creating directory \$targetdir" >&2
+	tmpdir="\$targetdir"
+	dashp="-p"
+    else
+	tmpdir="\$TMPROOT/selfgz\$\$\$RANDOM"
+	dashp=""
+    fi
+    mkdir \$dashp \$tmpdir || {
+	echo 'Cannot create target directory' \$tmpdir >&2
+	echo 'You should try option --target OtherDirectory' >&2
+	eval \$finish
+	exit 1
+    }
+fi
+
+location="\`pwd\`"
+if test x\$SETUP_NOCHECK != x1; then
+    MS_Check "\$0"
+fi
+offset=\`head -n $SKIP "\$0" | wc -c | tr -d " "\`
+
+if test x"\$verbose" = xy; then
+	MS_Printf "About to extract $USIZE KB in \$tmpdir ... Proceed ? [Y/n] "
+	read yn
+	if test x"\$yn" = xn; then
+		eval \$finish; exit 1
+	fi
+fi
+
+MS_Printf "Uncompressing \$label"
+res=3
+if test "\$keep" = n; then
+    trap 'echo Signal caught, cleaning up >&2; cd \$TMPROOT; /bin/rm -rf \$tmpdir; eval \$finish; exit 15' 1 2 3 15
+fi
+
+leftspace=\`MS_diskspace \$tmpdir\`
+if test \$leftspace -lt $USIZE; then
+    echo
+    echo "Not enough space left in "\`dirname \$tmpdir\`" (\$leftspace KB) to decompress \$0 ($USIZE KB)" >&2
+    if test "\$keep" = n; then
+        echo "Consider setting TMPDIR to a directory with more free space."
+   fi
+    eval \$finish; exit 1
+fi
+
+for s in \$filesizes
+do
+    if MS_dd "\$0" \$offset \$s | eval "$GUNZIP_CMD" | ( cd "\$tmpdir"; UnTAR x ) | MS_Progress; then
+		if test x"\$ownership" = xy; then
+			(PATH=/usr/xpg4/bin:\$PATH; cd "\$tmpdir"; chown -R \`id -u\` .;  chgrp -R \`id -g\` .)
+		fi
+    else
+		echo
+		echo "Unable to decompress \$0" >&2
+		eval \$finish; exit 1
+    fi
+    offset=\`expr \$offset + \$s\`
+done
+echo
+
+cd "\$tmpdir"
+res=0
+if test x"\$script" != x; then
+    if test x"\$verbose" = xy; then
+		MS_Printf "OK to execute: \$script \$scriptargs \$* ? [Y/n] "
+		read yn
+		if test x"\$yn" = x -o x"\$yn" = xy -o x"\$yn" = xY; then
+			eval \$script \$scriptargs \$*; res=\$?;
+		fi
+    else
+		eval \$script \$scriptargs \$*; res=\$?
+    fi
+    if test \$res -ne 0; then
+		test x"\$verbose" = xy && echo "The program '\$script' returned an error code (\$res)" >&2
+    fi
+fi
+if test "\$keep" = n; then
+    cd \$TMPROOT
+    /bin/rm -rf \$tmpdir
+fi
+eval \$finish; exit \$res
+EOF
--- a/sbsv2/raptor/util/install-linux/makeself.sh	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/install-linux/makeself.sh	Wed Jun 23 16:56:47 2010 +0800
@@ -1,407 +1,407 @@
-#!/bin/sh
-#
-# Makeself version 2.1.x
-#  by Stephane Peter <megastep@megastep.org>
-#
-# $Id: makeself.sh,v 1.64 2008/01/04 23:52:14 megastep Exp $
-#
-# Utility to create self-extracting tar.gz archives.
-# The resulting archive is a file holding the tar.gz archive with
-# a small Shell script stub that uncompresses the archive to a temporary
-# directory and then executes a given script from withing that directory.
-#
-# Makeself home page: http://www.megastep.org/makeself/
-#
-# Version 2.0 is a rewrite of version 1.0 to make the code easier to read and maintain.
-#
-# Version history :
-# - 1.0 : Initial public release
-# - 1.1 : The archive can be passed parameters that will be passed on to
-#         the embedded script, thanks to John C. Quillan
-# - 1.2 : Package distribution, bzip2 compression, more command line options,
-#         support for non-temporary archives. Ideas thanks to Francois Petitjean
-# - 1.3 : More patches from Bjarni R. Einarsson and Francois Petitjean:
-#         Support for no compression (--nocomp), script is no longer mandatory,
-#         automatic launch in an xterm, optional verbose output, and -target 
-#         archive option to indicate where to extract the files.
-# - 1.4 : Improved UNIX compatibility (Francois Petitjean)
-#         Automatic integrity checking, support of LSM files (Francois Petitjean)
-# - 1.5 : Many bugfixes. Optionally disable xterm spawning.
-# - 1.5.1 : More bugfixes, added archive options -list and -check.
-# - 1.5.2 : Cosmetic changes to inform the user of what's going on with big 
-#           archives (Quake III demo)
-# - 1.5.3 : Check for validity of the DISPLAY variable before launching an xterm.
-#           More verbosity in xterms and check for embedded command's return value.
-#           Bugfix for Debian 2.0 systems that have a different "print" command.
-# - 1.5.4 : Many bugfixes. Print out a message if the extraction failed.
-# - 1.5.5 : More bugfixes. Added support for SETUP_NOCHECK environment variable to
-#           bypass checksum verification of archives.
-# - 1.6.0 : Compute MD5 checksums with the md5sum command (patch from Ryan Gordon)
-# - 2.0   : Brand new rewrite, cleaner architecture, separated header and UNIX ports.
-# - 2.0.1 : Added --copy
-# - 2.1.0 : Allow multiple tarballs to be stored in one archive, and incremental updates.
-#           Added --nochown for archives
-#           Stopped doing redundant checksums when not necesary
-# - 2.1.1 : Work around insane behavior from certain Linux distros with no 'uncompress' command
-#           Cleaned up the code to handle error codes from compress. Simplified the extraction code.
-# - 2.1.2 : Some bug fixes. Use head -n to avoid problems.
-# - 2.1.3 : Bug fixes with command line when spawning terminals.
-#           Added --tar for archives, allowing to give arbitrary arguments to tar on the contents of the archive.
-#           Added --noexec to prevent execution of embedded scripts.
-#           Added --nomd5 and --nocrc to avoid creating checksums in archives.
-#           Added command used to create the archive in --info output.
-#           Run the embedded script through eval.
-# - 2.1.4 : Fixed --info output.
-#           Generate random directory name when extracting files to . to avoid problems. (Jason Trent)
-#           Better handling of errors with wrong permissions for the directory containing the files. (Jason Trent)
-#           Avoid some race conditions (Ludwig Nussel)
-#           Unset the $CDPATH variable to avoid problems if it is set. (Debian)
-#           Better handling of dot files in the archive directory.
-# - 2.1.5 : Made the md5sum detection consistent with the header code.
-#           Check for the presence of the archive directory
-#           Added --encrypt for symmetric encryption through gpg (Eric Windisch)
-#           Added support for the digest command on Solaris 10 for MD5 checksums
-#           Check for available disk space before extracting to the target directory (Andreas Schweitzer)
-#           Allow extraction to run asynchronously (patch by Peter Hatch)
-#           Use file descriptors internally to avoid error messages (patch by Kay Tiong Khoo)
-#
-# (C) 1998-2008 by Stéphane Peter <megastep@megastep.org>
-#
-# This software is released under the terms of the GNU GPL version 2 and above
-# Please read the license at http://www.gnu.org/copyleft/gpl.html
-#
-
-MS_VERSION=2.1.5
-MS_COMMAND="$0"
-unset CDPATH
-
-for f in "${1+"$@"}"; do
-    MS_COMMAND="$MS_COMMAND \\\\
-    \\\"$f\\\""
-done
-
-# Procedures
-
-MS_Usage()
-{
-    echo "Usage: $0 [params] archive_dir file_name label [startup_script] [args]"
-    echo "params can be one or more of the following :"
-    echo "    --version | -v  : Print out Makeself version number and exit"
-    echo "    --help | -h     : Print out this help message"
-    echo "    --gzip          : Compress using gzip (default if detected)"
-    echo "    --bzip2         : Compress using bzip2 instead of gzip"
-    echo "    --compress      : Compress using the UNIX 'compress' command"
-    echo "    --nocomp        : Do not compress the data"
-    echo "    --notemp        : The archive will create archive_dir in the"
-    echo "                      current directory and uncompress in ./archive_dir"
-    echo "    --copy          : Upon extraction, the archive will first copy itself to"
-    echo "                      a temporary directory"
-    echo "    --append        : Append more files to an existing Makeself archive"
-    echo "                      The label and startup scripts will then be ignored"
-    echo "    --current       : Files will be extracted to the current directory."
-    echo "                      Implies --notemp."
-    echo "    --nomd5         : Don't calculate an MD5 for archive"
-    echo "    --nocrc         : Don't calculate a CRC for archive"
-    echo "    --header file   : Specify location of the header script"
-    echo "    --follow        : Follow the symlinks in the archive"
-    echo "    --nox11         : Disable automatic spawn of a xterm"
-    echo "    --nowait        : Do not wait for user input after executing embedded"
-    echo "                      program from an xterm"
-    echo "    --lsm file      : LSM file describing the package"
-    echo
-    echo "Do not forget to give a fully qualified startup script name"
-    echo "(i.e. with a ./ prefix if inside the archive)."
-    exit 1
-}
-
-# Default settings
-if type gzip 2>&1 > /dev/null; then
-    COMPRESS=gzip
-else
-    COMPRESS=Unix
-fi
-KEEP=n
-CURRENT=n
-NOX11=n
-APPEND=n
-COPY=none
-TAR_ARGS=cvf
-HEADER=`dirname $0`/makeself-header.sh
-
-# LSM file stuff
-LSM_CMD="echo No LSM. >> \"\$archname\""
-
-while true
-do
-    case "$1" in
-    --version | -v)
-	echo Makeself version $MS_VERSION
-	exit 0
-	;;
-    --bzip2)
-	COMPRESS=bzip2
-	shift
-	;;
-    --gzip)
-	COMPRESS=gzip
-	shift
-	;;
-    --compress)
-	COMPRESS=Unix
-	shift
-	;;
-    --encrypt)
-	COMPRESS=gpg
-	shift
-	;;
-    --nocomp)
-	COMPRESS=none
-	shift
-	;;
-    --notemp)
-	KEEP=y
-	shift
-	;;
-    --copy)
-	COPY=copy
-	shift
-	;;
-    --current)
-	CURRENT=y
-	KEEP=y
-	shift
-	;;
-    --header)
-	HEADER="$2"
-	shift 2
-	;;
-    --follow)
-	TAR_ARGS=cvfh
-	shift
-	;;
-    --nox11)
-	NOX11=y
-	shift
-	;;
-    --nowait)
-	shift
-	;;
-    --nomd5)
-	NOMD5=y
-	shift
-	;;
-    --nocrc)
-	NOCRC=y
-	shift
-	;;
-    --append)
-	APPEND=y
-	shift
-	;;
-    --lsm)
-	LSM_CMD="cat \"$2\" >> \"\$archname\""
-	shift 2
-	;;
-    -h | --help)
-	MS_Usage
-	;;
-    -*)
-	echo Unrecognized flag : "$1"
-	MS_Usage
-	;;
-    *)
-	break
-	;;
-    esac
-done
-
-if test $# -lt 1; then
-	MS_Usage
-else
-	if test -d "$1"; then
-		archdir="$1"
-	else
-		echo "Directory $1 does not exist."
-		exit 1
-	fi
-fi
-archname="$2"
-
-if test "$APPEND" = y; then
-    if test $# -lt 2; then
-	MS_Usage
-    fi
-
-    # Gather the info from the original archive
-    OLDENV=`sh "$archname" --dumpconf`
-    if test $? -ne 0; then
-	echo "Unable to update archive: $archname" >&2
-	exit 1
-    else
-	eval "$OLDENV"
-    fi
-else
-    if test "$KEEP" = n -a $# = 3; then
-	echo "ERROR: Making a temporary archive with no embedded command does not make sense!" >&2
-	echo
-	MS_Usage
-    fi
-    # We don't really want to create an absolute directory...
-    if test "$CURRENT" = y; then
-	archdirname="."
-    else
-	archdirname=`basename "$1"`
-    fi
-
-    if test $# -lt 3; then
-	MS_Usage
-    fi
-
-    LABEL="$3"
-    SCRIPT="$4"
-    test x$SCRIPT = x || shift 1
-    shift 3
-    SCRIPTARGS="$*"
-fi
-
-if test "$KEEP" = n -a "$CURRENT" = y; then
-    echo "ERROR: It is A VERY DANGEROUS IDEA to try to combine --notemp and --current." >&2
-    exit 1
-fi
-
-case $COMPRESS in
-gzip)
-    GZIP_CMD="gzip -c9"
-    GUNZIP_CMD="gzip -cd"
-    ;;
-bzip2)
-    GZIP_CMD="bzip2 -9"
-    GUNZIP_CMD="bzip2 -d"
-    ;;
-gpg)
-    GZIP_CMD="gpg -ac -z9"
-    GUNZIP_CMD="gpg -d"
-    ;;
-Unix)
-    GZIP_CMD="compress -cf"
-    GUNZIP_CMD="exec 2>&-; uncompress -c || test \\\$? -eq 2 || gzip -cd"
-    ;;
-none)
-    GZIP_CMD="cat"
-    GUNZIP_CMD="cat"
-    ;;
-esac
-
-tmpfile="${TMPDIR:=/tmp}/mkself$$"
-
-if test -f $HEADER; then
-	oldarchname="$archname"
-	archname="$tmpfile"
-	# Generate a fake header to count its lines
-	SKIP=0
-    . $HEADER
-    SKIP=`cat "$tmpfile" |wc -l`
-	# Get rid of any spaces
-	SKIP=`expr $SKIP`
-	rm -f "$tmpfile"
-    echo Header is $SKIP lines long >&2
-
-	archname="$oldarchname"
-else
-    echo "Unable to open header file: $HEADER" >&2
-    exit 1
-fi
-
-echo
-
-if test "$APPEND" = n; then
-    if test -f "$archname"; then
-		echo "WARNING: Overwriting existing file: $archname" >&2
-    fi
-fi
-
-USIZE=`du -ks $archdir | cut -f1`
-DATE=`LC_ALL=C date`
-
-if test "." = "$archdirname"; then
-	if test "$KEEP" = n; then
-		archdirname="makeself-$$-`date +%Y%m%d%H%M%S`"
-	fi
-fi
-
-test -d "$archdir" || { echo "Error: $archdir does not exist."; rm -f "$tmpfile"; exit 1; }
-echo About to compress $USIZE KB of data...
-echo Adding files to archive named \"$archname\"...
-exec 3<> "$tmpfile"
-(cd "$archdir" && ( tar $TAR_ARGS - . | eval "$GZIP_CMD" >&3 ) ) || { echo Aborting: Archive directory not found or temporary file: "$tmpfile" could not be created.; exec 3>&-; rm -f "$tmpfile"; exit 1; }
-exec 3>&- # try to close the archive
-
-fsize=`cat "$tmpfile" | wc -c | tr -d " "`
-
-# Compute the checksums
-
-md5sum=00000000000000000000000000000000
-crcsum=0000000000
-
-if test "$NOCRC" = y; then
-	echo "skipping crc at user request"
-else
-	crcsum=`cat "$tmpfile" | CMD_ENV=xpg4 cksum | sed -e 's/ /Z/' -e 's/	/Z/' | cut -dZ -f1`
-	echo "CRC: $crcsum"
-fi
-
-if test "$NOMD5" = y; then
-	echo "skipping md5sum at user request"
-else
-	# Try to locate a MD5 binary
-	OLD_PATH=$PATH
-	PATH=${GUESS_MD5_PATH:-"$OLD_PATH:/bin:/usr/bin:/sbin:/usr/local/ssl/bin:/usr/local/bin:/opt/openssl/bin"}
-	MD5_ARG=""
-	MD5_PATH=`exec <&- 2>&-; which md5sum || type md5sum`
-	test -x $MD5_PATH || MD5_PATH=`exec <&- 2>&-; which md5 || type md5`
-	test -x $MD5_PATH || MD5_PATH=`exec <&- 2>&-; which digest || type digest`
-	PATH=$OLD_PATH
-	if test `basename $MD5_PATH` = digest; then
-		MD5_ARG="-a md5"
-	fi
-	if test -x "$MD5_PATH"; then
-		md5sum=`cat "$tmpfile" | eval "$MD5_PATH $MD5_ARG" | cut -b-32`;
-		echo "MD5: $md5sum"
-	else
-		echo "MD5: none, MD5 command not found"
-	fi
-fi
-
-if test "$APPEND" = y; then
-    mv "$archname" "$archname".bak || exit
-
-    # Prepare entry for new archive
-    filesizes="$filesizes $fsize"
-    CRCsum="$CRCsum $crcsum"
-    MD5sum="$MD5sum $md5sum"
-    USIZE=`expr $USIZE + $OLDUSIZE`
-    # Generate the header
-    . $HEADER
-    # Append the original data
-    tail -n +$OLDSKIP "$archname".bak >> "$archname"
-    # Append the new data
-    cat "$tmpfile" >> "$archname"
-
-    chmod +x "$archname"
-    rm -f "$archname".bak
-    echo Self-extractible archive \"$archname\" successfully updated.
-else
-    filesizes="$fsize"
-    CRCsum="$crcsum"
-    MD5sum="$md5sum"
-
-    # Generate the header
-    . $HEADER
-
-    # Append the compressed tar data after the stub
-    echo
-    cat "$tmpfile" >> "$archname"
-    chmod +x "$archname"
-    echo Self-extractible archive \"$archname\" successfully created.
-fi
-rm -f "$tmpfile"
+#!/bin/sh
+#
+# Makeself version 2.1.x
+#  by Stephane Peter <megastep@megastep.org>
+#
+# $Id: makeself.sh,v 1.64 2008/01/04 23:52:14 megastep Exp $
+#
+# Utility to create self-extracting tar.gz archives.
+# The resulting archive is a file holding the tar.gz archive with
+# a small Shell script stub that uncompresses the archive to a temporary
+# directory and then executes a given script from withing that directory.
+#
+# Makeself home page: http://www.megastep.org/makeself/
+#
+# Version 2.0 is a rewrite of version 1.0 to make the code easier to read and maintain.
+#
+# Version history :
+# - 1.0 : Initial public release
+# - 1.1 : The archive can be passed parameters that will be passed on to
+#         the embedded script, thanks to John C. Quillan
+# - 1.2 : Package distribution, bzip2 compression, more command line options,
+#         support for non-temporary archives. Ideas thanks to Francois Petitjean
+# - 1.3 : More patches from Bjarni R. Einarsson and Francois Petitjean:
+#         Support for no compression (--nocomp), script is no longer mandatory,
+#         automatic launch in an xterm, optional verbose output, and -target 
+#         archive option to indicate where to extract the files.
+# - 1.4 : Improved UNIX compatibility (Francois Petitjean)
+#         Automatic integrity checking, support of LSM files (Francois Petitjean)
+# - 1.5 : Many bugfixes. Optionally disable xterm spawning.
+# - 1.5.1 : More bugfixes, added archive options -list and -check.
+# - 1.5.2 : Cosmetic changes to inform the user of what's going on with big 
+#           archives (Quake III demo)
+# - 1.5.3 : Check for validity of the DISPLAY variable before launching an xterm.
+#           More verbosity in xterms and check for embedded command's return value.
+#           Bugfix for Debian 2.0 systems that have a different "print" command.
+# - 1.5.4 : Many bugfixes. Print out a message if the extraction failed.
+# - 1.5.5 : More bugfixes. Added support for SETUP_NOCHECK environment variable to
+#           bypass checksum verification of archives.
+# - 1.6.0 : Compute MD5 checksums with the md5sum command (patch from Ryan Gordon)
+# - 2.0   : Brand new rewrite, cleaner architecture, separated header and UNIX ports.
+# - 2.0.1 : Added --copy
+# - 2.1.0 : Allow multiple tarballs to be stored in one archive, and incremental updates.
+#           Added --nochown for archives
+#           Stopped doing redundant checksums when not necesary
+# - 2.1.1 : Work around insane behavior from certain Linux distros with no 'uncompress' command
+#           Cleaned up the code to handle error codes from compress. Simplified the extraction code.
+# - 2.1.2 : Some bug fixes. Use head -n to avoid problems.
+# - 2.1.3 : Bug fixes with command line when spawning terminals.
+#           Added --tar for archives, allowing to give arbitrary arguments to tar on the contents of the archive.
+#           Added --noexec to prevent execution of embedded scripts.
+#           Added --nomd5 and --nocrc to avoid creating checksums in archives.
+#           Added command used to create the archive in --info output.
+#           Run the embedded script through eval.
+# - 2.1.4 : Fixed --info output.
+#           Generate random directory name when extracting files to . to avoid problems. (Jason Trent)
+#           Better handling of errors with wrong permissions for the directory containing the files. (Jason Trent)
+#           Avoid some race conditions (Ludwig Nussel)
+#           Unset the $CDPATH variable to avoid problems if it is set. (Debian)
+#           Better handling of dot files in the archive directory.
+# - 2.1.5 : Made the md5sum detection consistent with the header code.
+#           Check for the presence of the archive directory
+#           Added --encrypt for symmetric encryption through gpg (Eric Windisch)
+#           Added support for the digest command on Solaris 10 for MD5 checksums
+#           Check for available disk space before extracting to the target directory (Andreas Schweitzer)
+#           Allow extraction to run asynchronously (patch by Peter Hatch)
+#           Use file descriptors internally to avoid error messages (patch by Kay Tiong Khoo)
+#
+# (C) 1998-2008 by Stéphane Peter <megastep@megastep.org>
+#
+# This software is released under the terms of the GNU GPL version 2 and above
+# Please read the license at http://www.gnu.org/copyleft/gpl.html
+#
+
+MS_VERSION=2.1.5
+MS_COMMAND="$0"
+unset CDPATH
+
+for f in "${1+"$@"}"; do
+    MS_COMMAND="$MS_COMMAND \\\\
+    \\\"$f\\\""
+done
+
+# Procedures
+
+MS_Usage()
+{
+    echo "Usage: $0 [params] archive_dir file_name label [startup_script] [args]"
+    echo "params can be one or more of the following :"
+    echo "    --version | -v  : Print out Makeself version number and exit"
+    echo "    --help | -h     : Print out this help message"
+    echo "    --gzip          : Compress using gzip (default if detected)"
+    echo "    --bzip2         : Compress using bzip2 instead of gzip"
+    echo "    --compress      : Compress using the UNIX 'compress' command"
+    echo "    --nocomp        : Do not compress the data"
+    echo "    --notemp        : The archive will create archive_dir in the"
+    echo "                      current directory and uncompress in ./archive_dir"
+    echo "    --copy          : Upon extraction, the archive will first copy itself to"
+    echo "                      a temporary directory"
+    echo "    --append        : Append more files to an existing Makeself archive"
+    echo "                      The label and startup scripts will then be ignored"
+    echo "    --current       : Files will be extracted to the current directory."
+    echo "                      Implies --notemp."
+    echo "    --nomd5         : Don't calculate an MD5 for archive"
+    echo "    --nocrc         : Don't calculate a CRC for archive"
+    echo "    --header file   : Specify location of the header script"
+    echo "    --follow        : Follow the symlinks in the archive"
+    echo "    --nox11         : Disable automatic spawn of a xterm"
+    echo "    --nowait        : Do not wait for user input after executing embedded"
+    echo "                      program from an xterm"
+    echo "    --lsm file      : LSM file describing the package"
+    echo
+    echo "Do not forget to give a fully qualified startup script name"
+    echo "(i.e. with a ./ prefix if inside the archive)."
+    exit 1
+}
+
+# Default settings
+if type gzip 2>&1 > /dev/null; then
+    COMPRESS=gzip
+else
+    COMPRESS=Unix
+fi
+KEEP=n
+CURRENT=n
+NOX11=n
+APPEND=n
+COPY=none
+TAR_ARGS=cvf
+HEADER=`dirname $0`/makeself-header.sh
+
+# LSM file stuff
+LSM_CMD="echo No LSM. >> \"\$archname\""
+
+while true
+do
+    case "$1" in
+    --version | -v)
+	echo Makeself version $MS_VERSION
+	exit 0
+	;;
+    --bzip2)
+	COMPRESS=bzip2
+	shift
+	;;
+    --gzip)
+	COMPRESS=gzip
+	shift
+	;;
+    --compress)
+	COMPRESS=Unix
+	shift
+	;;
+    --encrypt)
+	COMPRESS=gpg
+	shift
+	;;
+    --nocomp)
+	COMPRESS=none
+	shift
+	;;
+    --notemp)
+	KEEP=y
+	shift
+	;;
+    --copy)
+	COPY=copy
+	shift
+	;;
+    --current)
+	CURRENT=y
+	KEEP=y
+	shift
+	;;
+    --header)
+	HEADER="$2"
+	shift 2
+	;;
+    --follow)
+	TAR_ARGS=cvfh
+	shift
+	;;
+    --nox11)
+	NOX11=y
+	shift
+	;;
+    --nowait)
+	shift
+	;;
+    --nomd5)
+	NOMD5=y
+	shift
+	;;
+    --nocrc)
+	NOCRC=y
+	shift
+	;;
+    --append)
+	APPEND=y
+	shift
+	;;
+    --lsm)
+	LSM_CMD="cat \"$2\" >> \"\$archname\""
+	shift 2
+	;;
+    -h | --help)
+	MS_Usage
+	;;
+    -*)
+	echo Unrecognized flag : "$1"
+	MS_Usage
+	;;
+    *)
+	break
+	;;
+    esac
+done
+
+if test $# -lt 1; then
+	MS_Usage
+else
+	if test -d "$1"; then
+		archdir="$1"
+	else
+		echo "Directory $1 does not exist."
+		exit 1
+	fi
+fi
+archname="$2"
+
+if test "$APPEND" = y; then
+    if test $# -lt 2; then
+	MS_Usage
+    fi
+
+    # Gather the info from the original archive
+    OLDENV=`sh "$archname" --dumpconf`
+    if test $? -ne 0; then
+	echo "Unable to update archive: $archname" >&2
+	exit 1
+    else
+	eval "$OLDENV"
+    fi
+else
+    if test "$KEEP" = n -a $# = 3; then
+	echo "ERROR: Making a temporary archive with no embedded command does not make sense!" >&2
+	echo
+	MS_Usage
+    fi
+    # We don't really want to create an absolute directory...
+    if test "$CURRENT" = y; then
+	archdirname="."
+    else
+	archdirname=`basename "$1"`
+    fi
+
+    if test $# -lt 3; then
+	MS_Usage
+    fi
+
+    LABEL="$3"
+    SCRIPT="$4"
+    test x$SCRIPT = x || shift 1
+    shift 3
+    SCRIPTARGS="$*"
+fi
+
+if test "$KEEP" = n -a "$CURRENT" = y; then
+    echo "ERROR: It is A VERY DANGEROUS IDEA to try to combine --notemp and --current." >&2
+    exit 1
+fi
+
+case $COMPRESS in
+gzip)
+    GZIP_CMD="gzip -c9"
+    GUNZIP_CMD="gzip -cd"
+    ;;
+bzip2)
+    GZIP_CMD="bzip2 -9"
+    GUNZIP_CMD="bzip2 -d"
+    ;;
+gpg)
+    GZIP_CMD="gpg -ac -z9"
+    GUNZIP_CMD="gpg -d"
+    ;;
+Unix)
+    GZIP_CMD="compress -cf"
+    GUNZIP_CMD="exec 2>&-; uncompress -c || test \\\$? -eq 2 || gzip -cd"
+    ;;
+none)
+    GZIP_CMD="cat"
+    GUNZIP_CMD="cat"
+    ;;
+esac
+
+tmpfile="${TMPDIR:=/tmp}/mkself$$"
+
+if test -f $HEADER; then
+	oldarchname="$archname"
+	archname="$tmpfile"
+	# Generate a fake header to count its lines
+	SKIP=0
+    . $HEADER
+    SKIP=`cat "$tmpfile" |wc -l`
+	# Get rid of any spaces
+	SKIP=`expr $SKIP`
+	rm -f "$tmpfile"
+    echo Header is $SKIP lines long >&2
+
+	archname="$oldarchname"
+else
+    echo "Unable to open header file: $HEADER" >&2
+    exit 1
+fi
+
+echo
+
+if test "$APPEND" = n; then
+    if test -f "$archname"; then
+		echo "WARNING: Overwriting existing file: $archname" >&2
+    fi
+fi
+
+USIZE=`du -ks $archdir | cut -f1`
+DATE=`LC_ALL=C date`
+
+if test "." = "$archdirname"; then
+	if test "$KEEP" = n; then
+		archdirname="makeself-$$-`date +%Y%m%d%H%M%S`"
+	fi
+fi
+
+test -d "$archdir" || { echo "Error: $archdir does not exist."; rm -f "$tmpfile"; exit 1; }
+echo About to compress $USIZE KB of data...
+echo Adding files to archive named \"$archname\"...
+exec 3<> "$tmpfile"
+(cd "$archdir" && ( tar $TAR_ARGS - . | eval "$GZIP_CMD" >&3 ) ) || { echo Aborting: Archive directory not found or temporary file: "$tmpfile" could not be created.; exec 3>&-; rm -f "$tmpfile"; exit 1; }
+exec 3>&- # try to close the archive
+
+fsize=`cat "$tmpfile" | wc -c | tr -d " "`
+
+# Compute the checksums
+
+md5sum=00000000000000000000000000000000
+crcsum=0000000000
+
+if test "$NOCRC" = y; then
+	echo "skipping crc at user request"
+else
+	crcsum=`cat "$tmpfile" | CMD_ENV=xpg4 cksum | sed -e 's/ /Z/' -e 's/	/Z/' | cut -dZ -f1`
+	echo "CRC: $crcsum"
+fi
+
+if test "$NOMD5" = y; then
+	echo "skipping md5sum at user request"
+else
+	# Try to locate a MD5 binary
+	OLD_PATH=$PATH
+	PATH=${GUESS_MD5_PATH:-"$OLD_PATH:/bin:/usr/bin:/sbin:/usr/local/ssl/bin:/usr/local/bin:/opt/openssl/bin"}
+	MD5_ARG=""
+	MD5_PATH=`exec <&- 2>&-; which md5sum || type md5sum`
+	test -x $MD5_PATH || MD5_PATH=`exec <&- 2>&-; which md5 || type md5`
+	test -x $MD5_PATH || MD5_PATH=`exec <&- 2>&-; which digest || type digest`
+	PATH=$OLD_PATH
+	if test `basename $MD5_PATH` = digest; then
+		MD5_ARG="-a md5"
+	fi
+	if test -x "$MD5_PATH"; then
+		md5sum=`cat "$tmpfile" | eval "$MD5_PATH $MD5_ARG" | cut -b-32`;
+		echo "MD5: $md5sum"
+	else
+		echo "MD5: none, MD5 command not found"
+	fi
+fi
+
+if test "$APPEND" = y; then
+    mv "$archname" "$archname".bak || exit
+
+    # Prepare entry for new archive
+    filesizes="$filesizes $fsize"
+    CRCsum="$CRCsum $crcsum"
+    MD5sum="$MD5sum $md5sum"
+    USIZE=`expr $USIZE + $OLDUSIZE`
+    # Generate the header
+    . $HEADER
+    # Append the original data
+    tail -n +$OLDSKIP "$archname".bak >> "$archname"
+    # Append the new data
+    cat "$tmpfile" >> "$archname"
+
+    chmod +x "$archname"
+    rm -f "$archname".bak
+    echo Self-extractible archive \"$archname\" successfully updated.
+else
+    filesizes="$fsize"
+    CRCsum="$crcsum"
+    MD5sum="$md5sum"
+
+    # Generate the header
+    . $HEADER
+
+    # Append the compressed tar data after the stub
+    echo
+    cat "$tmpfile" >> "$archname"
+    chmod +x "$archname"
+    echo Self-extractible archive \"$archname\" successfully created.
+fi
+rm -f "$tmpfile"
--- a/sbsv2/raptor/util/install-linux/package_sbs.sh	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/install-linux/package_sbs.sh	Wed Jun 23 16:56:47 2010 +0800
@@ -1,83 +1,83 @@
-#!/bin/bash
-
-# 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:
-# Package into a linux .run file
-#
-#
-
-getopts 's' packopt
-
-
-export packtype=binary
-if [[ "$packopt" == "s" ]]; then
-packtype=source
-fi
-
-echo "Raptor packager for Linux"
-export PACKAGER_HOME="$PWD"
-
-echo "SBS_HOME is $SBS_HOME - this is the version that will be packaged."
-
-export FULLVERSION=`$SBS_HOME/bin/sbs -v` # this also generates all the pyc files
-export VERSION=`echo "$FULLVERSION" | sed 's#.*sbs version *\([^ ]*\).*#\1#'`
-
-if [ -z "$VERSION" ]; then
-	echo "Version could not be automatically determined - check that SBS_HOME is set correctly" 1>&2
-	exit 1
-else
-	echo "Packaging version $FULLVERSION"
-fi
-
-HOSTPLATFORM_DIR=$($SBS_HOME/bin/gethost.sh -d)
-
-if [[ "$packtype" == "source" ]]; then
-HOSTPLATFORM_DIR="linux_source"
-fi
-
-
-export DIRNAME=sbs-$VERSION-$HOSTPLATFORM_DIR
-export TMPSBS=/tmp/$DIRNAME
-if [ -d  "$TMPSBS" ]; then
-	rm -rf "$TMPSBS"
-fi
-set -x
-mkdir -p "$TMPSBS" &&
-(
-BINARIES="$HOSTPLATFORM_DIR"
-if [[ "$packtype" == "source" ]]; then
-BINARIES=""
-fi
-
-
-   echo init.xml LICENSE.txt RELEASE-NOTES.txt; cd $SBS_HOME && find bin lib $BINARIES python test schema util |
-	grep -v "$TMPSBS"'/python/\.py$' |
-	grep -v 'flm/test'  |
-	grep -v 'util/build'  | 
-	grep -v 'test/epocroot/epoc32/build'  | 
-	grep -v '~$'  |  cpio -o --quiet  2>/dev/null 
-) | ( cd "$TMPSBS" && cpio -i --make-directories  --quiet >/dev/null 2>&1)
-
-# store the version number
-echo "FULLVERSION=\"$FULLVERSION\"" > $TMPSBS/.version
-echo "VERSION=\"$VERSION\"" >> $TMPSBS/.version
-
-if [[ "$packtype" == "binary" ]]; then
-chmod a+x $TMPSBS/bin/* $TMPSBS/util/$HOSTPLATFORM_DIR/bin/* $TMPSBS/util/$HOSTPLATFORM_DIR/python262/bin/* 
-chmod a+x $TMPSBS/util/pvm3/bin/LINUX/*
-chmod a+x $TMPSBS/util/$HOSTPLATFORM_DIR/cw_build470msl19/release/Symbian_Tools/Command_Line_Tools/*
-fi
-
-cd $TMPSBS/.. && bash "$PACKAGER_HOME"/makeself.sh $DIRNAME $DIRNAME.run "$FULLVERSION\n" ./bin/install_raptor.sh
-
+#!/bin/bash
+
+# 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:
+# Package into a linux .run file
+#
+#
+
+getopts 's' packopt
+
+
+export packtype=binary
+if [[ "$packopt" == "s" ]]; then
+packtype=source
+fi
+
+echo "Raptor packager for Linux"
+export PACKAGER_HOME="$PWD"
+
+echo "SBS_HOME is $SBS_HOME - this is the version that will be packaged."
+
+export FULLVERSION=`$SBS_HOME/bin/sbs -v` # this also generates all the pyc files
+export VERSION=`echo "$FULLVERSION" | sed 's#.*sbs version *\([^ ]*\).*#\1#'`
+
+if [ -z "$VERSION" ]; then
+	echo "Version could not be automatically determined - check that SBS_HOME is set correctly" 1>&2
+	exit 1
+else
+	echo "Packaging version $FULLVERSION"
+fi
+
+HOSTPLATFORM_DIR=$($SBS_HOME/bin/gethost.sh -d)
+
+if [[ "$packtype" == "source" ]]; then
+HOSTPLATFORM_DIR="linux_source"
+fi
+
+
+export DIRNAME=sbs-$VERSION-$HOSTPLATFORM_DIR
+export TMPSBS=/tmp/$DIRNAME
+if [ -d  "$TMPSBS" ]; then
+	rm -rf "$TMPSBS"
+fi
+set -x
+mkdir -p "$TMPSBS" &&
+(
+BINARIES="$HOSTPLATFORM_DIR"
+if [[ "$packtype" == "source" ]]; then
+BINARIES=""
+fi
+
+
+   cd $SBS_HOME && find license.txt RELEASE-NOTES.html bin lib notes $BINARIES python test schema util |
+	grep -v "$TMPSBS"'/python/\.py$' |
+	grep -v 'flm/test'  |
+	grep -v 'util/build'  | 
+	grep -v 'test/epocroot/epoc32/build'  | 
+	grep -v '~$'  |  cpio -o --quiet  2>/dev/null 
+) | ( cd "$TMPSBS" && cpio -i --make-directories  --quiet >/dev/null 2>&1)
+
+# store the version number
+echo "FULLVERSION=\"$FULLVERSION\"" > $TMPSBS/.version
+echo "VERSION=\"$VERSION\"" >> $TMPSBS/.version
+
+if [[ "$packtype" == "binary" ]]; then
+chmod a+x $TMPSBS/bin/* $TMPSBS/util/$HOSTPLATFORM_DIR/bin/* $TMPSBS/util/$HOSTPLATFORM_DIR/python262/bin/* 
+chmod a+x $TMPSBS/util/pvm3/bin/LINUX/*
+chmod a+x $TMPSBS/util/$HOSTPLATFORM_DIR/cw_build470msl19/release/Symbian_Tools/Command_Line_Tools/*
+fi
+
+cd $TMPSBS/.. && bash "$PACKAGER_HOME"/makeself.sh $DIRNAME $DIRNAME.run "$FULLVERSION\n" ./bin/install_raptor.sh
+
--- a/sbsv2/raptor/util/install-windows/raptorinstallermaker.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/install-windows/raptorinstallermaker.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,105 +1,182 @@
-#
-# 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: 
-#
-#! python
-
-# Raptor installer maker!
-
-import os
-import os.path
-import subprocess
-import re
-import optparse
-import sys
-import tempfile
-import shutil
-import unzip
-
-tempdir = ""
-
-parser = optparse.OptionParser()
-parser.add_option("-s", "--sbs_home", dest="sbs_home",
-                  help="Path to use as SBS_HOME environment variable. If not present the script exits.")
-
-(options, args) = parser.parse_args()
-
-if options.sbs_home == None:
-	print "ERROR: no SBS_HOME passed in. Exiting..."
-	sys.exit(2)
-
-
-def parseconfig(xmlFile="raptorinstallermaker.xml"):
-	pass
-
-def generateinstallerversionheader(sbs_home = None):
-	os.environ["SBS_HOME"] = sbs_home
-	os.environ["PATH"] = os.path.join(os.environ["SBS_HOME"], "bin") + os.pathsep + os.environ["PATH"]
-	
-	versioncommand = "sbs -v"
-	
-	# Raptor version string looks like this
-	# sbs version 2.5.0 [2009-02-20 release]
-	sbs_version_matcher = re.compile(".*(\d+\.\d+\.\d+).*", re.I)
-	
-	# Create Raptor subprocess
-	sbs = subprocess.Popen(versioncommand, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
-	
-	# Get all the lines matching the RE
-	for line in sbs.stdout.readlines():
-		res = sbs_version_matcher.match(line)
-		if res:
-			raptorversion = res.group(1)
-			print "Successfully determined Raptor version %s" % raptorversion
-
-	sbs.wait() # Wait for process to end
-	
-	raptorversion_nsis_header_string = "# Raptor version file\n\n!define RAPTOR_VERSION %s\n" % raptorversion
-	
-	fh = open("raptorversion.nsh", "w")
-	fh.write(raptorversion_nsis_header_string)
-	fh.close()
-	print "Wrote raptorversion.nsh"
-	return 0
-	
-def unzipnsis(pathtozip):
-    global tempdir
-    tempdir = tempfile.mkdtemp()
-    un = unzip.unzip()
-    print "Unzipping NSIS to %s..." % tempdir
-    un.extract(pathtozip, tempdir)
-    print "Done."
-    
-    return os.path.join(tempdir, "NSIS", "makensis.exe")
-    
-def runmakensis(nsiscommand):
-	# Create makensis subprocess
-	print "Running NSIS command\n%s" % nsiscommand
-	makensis = subprocess.Popen(nsiscommand, shell=True)
-	makensis.wait() # Wait for process to end
-
-def cleanup():
-	""" Clean up tempdir """
-	global tempdir
-	print "Cleaning up temporary directory %s" % tempdir
-	shutil.rmtree(tempdir,True)
-	print "Done."
-
-makensispath = unzipnsis(".\\NSIS.zip")
-generateinstallerversionheader(options.sbs_home)
-nsiscommand = makensispath + " /DRAPTOR_LOCATION=%s raptorinstallerscript.nsi" % options.sbs_home
-print "nsiscommand = %s" % nsiscommand
-runmakensis(nsiscommand)
-cleanup()
-
+#
+# Copyright (c) 2009-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: 
+#
+#! python
+
+# Raptor installer maker!
+
+import os
+import os.path
+import subprocess
+import re
+import optparse
+import sys
+import tempfile
+import shutil
+import unzip
+
+tempdir = ""
+
+parser = optparse.OptionParser()
+
+parser.add_option("-s", "--sbs-home", dest="sbshome", help="Path to use as SBS_HOME environment variable. If not present the script exits.")
+
+parser.add_option("-w", "--win32-support", dest="win32support", help="Path to Win32 support directory. If not present the script exits.")
+
+parser.add_option("-b", "--bv", dest="bv", help="Path to Binary variation CPP \"root\" directory. Can be a full/relatitve path; prefix with \"WIN32SUPPORT\\\" to be relative to the Win32 support directory. Omitting this value will assume a default to a path inside the Win32 support directory.")
+
+parser.add_option("-c", "--cygwin", dest="cygwin", help="Path to Cygwin \"root\" directory. Can be a full/relatitve path; prefix with \"WIN32SUPPORT\\\" to be relative to the Win32 support directory. Omitting this value will assume a default to a path inside the Win32 support directory.")
+
+parser.add_option("-m", "--mingw", dest="mingw", help="Path to MinGW \"root\" directory. Can be a full/relatitve path; prefix with \"WIN32SUPPORT\\\" to be relative to the Win32 support directory. Omitting this value will assume a default to a path inside the Win32 support directory.")
+
+parser.add_option("-p", "--python", dest="python", help="Path to Python \"root\" directory. Can be a full/relatitve path; prefix with \"WIN32SUPPORT\\\" to be relative to the Win32 support directory. Omitting this value will assume a default to a path inside the Win32 support directory.")
+
+parser.add_option("--prefix", dest="versionprefix", help="A string to use as a prefix to the Raptor version string. This will be present in the Raptor installer's file name, the installer's pages as well as the in output from sbs -v.", type="string", default="")
+
+parser.add_option("--postfix", dest="versionpostfix", help="A string to use as a postfix to the Raptor version string. This will be present in the Raptor installer's file name, the installer's pages as well as the in output from sbs -v.", type="string", default="")
+
+(options, args) = parser.parse_args()
+
+# Required directories inside the win32-support repository
+win32supportdirs = {"bv":"bv", "cygwin":"cygwin", "mingw":"mingw", "python":"python264"}
+
+if options.sbshome == None:
+	print "ERROR: no SBS_HOME passed in. Exiting..."
+	sys.exit(2)
+
+if options.win32support == None:
+	print "ERROR: no win32support directory specified. Unable to proceed. Exiting..."
+	sys.exit(2)
+else:
+	# Check for command line overrides to defaults
+	for directory in win32supportdirs:
+		print "TEST %s" % directory
+		value = getattr(options,directory)
+		print "value =  %s" % str(value)
+		if value != None: # Command line override
+			if value.lower().startswith("win32support"):
+				# Strip off "WIN32SUPPORT\" and join to Win32 support location
+				win32supportdirs[directory] = os.path.join(options.win32support, value[13:]) 
+			else:
+				# Relative to current directory
+				win32supportdirs[directory] = value
+
+		else: # Use default location
+			win32supportdirs[directory] = os.path.join(options.win32support, win32supportdirs[directory])
+	
+	print "\n\nwin32supportdirs = %s\n\n" % win32supportdirs
+
+	# Check that all the specified directories exist and exit if any of them is missing.
+	for directory in win32supportdirs:
+		dir = win32supportdirs[directory]
+		if os.path.isdir(dir):
+			print "Found directory %s" % dir
+		else:
+			print "ERROR: directory %s does not exist. Cannot build installer. Exiting..." % dir
+			sys.exit(2)
+
+def generateinstallerversionheader(sbshome = None):
+	shellenv = os.environ.copy()
+	shellenv["PYTHONPATH"] = os.path.join(sbshome, "python")
+	
+	raptorversioncommand = "python -c \"import raptor_version; print raptor_version.numericversion()\""
+	
+	# Raptor version is obtained from raptor_version module's numericversion function.
+	sbs_version_matcher = re.compile(".*(\d+\.\d+\.\d+).*", re.I)
+	
+	# Create Raptor subprocess
+	versioncommand = subprocess.Popen(raptorversioncommand, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=shellenv)
+	raptorversion = ""
+	# Get all the lines matching the RE
+	for line in versioncommand.stdout.readlines():
+		res = sbs_version_matcher.match(line)
+		if res:
+			raptorversion = res.group(1)
+			print "Successfully determined Raptor version %s" % raptorversion
+
+	versioncommand.wait() # Wait for process to end
+	
+	raptorversion_nsis_header_string = "# Raptor version file\n\n!define RAPTOR_VERSION %s\n" % raptorversion
+	
+	fh = open("raptorversion.nsh", "w")
+	fh.write(raptorversion_nsis_header_string)
+	fh.close()
+	print "Wrote raptorversion.nsh"
+	return 0
+
+def generateinstallerversion(sbshome = None):
+	shellenv = os.environ.copy()
+	shellenv["PYTHONPATH"] = os.path.join(sbshome, "python")
+	
+	raptorversioncommand = "python -c \"import raptor_version; print raptor_version.numericversion()\""
+	
+	# Raptor version is obtained from raptor_version module's numericversion function.
+	sbs_version_matcher = re.compile(".*(\d+\.\d+\.\d+).*", re.I)
+	
+	# Create Raptor subprocess
+	versioncommand = subprocess.Popen(raptorversioncommand, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=shellenv)
+	raptorversion = ""
+	# Get all the lines matching the RE
+	for line in versioncommand.stdout.readlines():
+		res = sbs_version_matcher.match(line)
+		if res:
+			raptorversion = res.group(1)
+			print "Successfully determined Raptor version %s" % raptorversion
+
+	versioncommand.wait() # Wait for process to end
+	
+	return raptorversion
+	
+def unzipnsis(pathtozip):
+    global tempdir
+    tempdir = tempfile.mkdtemp()
+    un = unzip.unzip()
+    print "Unzipping NSIS to %s..." % tempdir
+    un.extract(pathtozip, tempdir)
+    print "Done."
+    
+    return os.path.join(tempdir, "NSIS", "makensis.exe")
+    
+def runmakensis(nsiscommand):
+	# Create makensis subprocess
+	print "Running NSIS command\n%s" % nsiscommand
+	makensis = subprocess.Popen(nsiscommand, shell=True)
+	makensis.wait() # Wait for process to end
+
+def cleanup():
+	""" Clean up tempdir """
+	global tempdir
+	print "Cleaning up temporary directory %s" % tempdir
+	shutil.rmtree(tempdir,True)
+	try:
+		os.remove("raptorversion.nsh")
+		print "Successfully deleted raptorversion.nsh."
+	except:
+		print "ERROR: failed to remove raptorversion.nsh - remove manually if needed."
+	print "Done."
+
+makensispath = unzipnsis(".\\NSIS.zip")
+# generateinstallerversionheader(options.sbshome)
+raptorversion = options.versionprefix + generateinstallerversion(options.sbshome) + options.versionpostfix
+nsiscommand = makensispath + " /DRAPTOR_LOCATION=%s /DBV_LOCATION=%s /DCYGWIN_LOCATION=%s /DMINGW_LOCATION=%s /DPYTHON_LOCATION=%s /DRAPTOR_VERSION=%s raptorinstallerscript.nsi" % (options.sbshome, 
+				win32supportdirs["bv"],
+				win32supportdirs["cygwin"],
+				win32supportdirs["mingw"],
+				win32supportdirs["python"],
+				raptorversion)
+print "nsiscommand = %s" % nsiscommand
+runmakensis(nsiscommand)
+cleanup()
+
--- a/sbsv2/raptor/util/install-windows/raptorinstallerscript.nsi	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/install-windows/raptorinstallerscript.nsi	Wed Jun 23 16:56:47 2010 +0800
@@ -1,486 +1,496 @@
-# 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: 
-# Raptor installer/uninstaller script
-
-# Standard NSIS Library includes 
-!include "MUI2.nsh"
-!include "LogicLib.nsh"
-!include "WinMessages.nsh"
-
-# Extra plugin includes
-!include "nsDialogs.nsh"
-!include "Registry.nsh"
-!include "NSISpcre.nsh"
-!include "Time.nsh"
-
-# Define functions from NSISpcre.nsh 
-!insertmacro REMatches
-!insertmacro un.REMatches
-!insertmacro REQuoteMeta
-
-# Variables
-Var DIALOG
-Var RESULT # Generic variable to obtain results, and immediately thrown away after
-Var RESULT2 # Generic variable to obtain results, and immediately thrown away after
-Var SBS_HOME
-Var USERONLYINSTALL_HWND # HWND of radio button control for user-only installation
-Var ALLUSERSINSTALL_HWND # HWND of radio button control for system installation
-Var NOENVCHANGES_HWND    # HWND of radio button control for file-only installation
-Var USERONLYINSTALL_STATE # State of user-only radio button
-Var ALLUSERSINSTALL_STATE # State of system radio button
-Var NOENVCHANGES_STATE # State of file-only installation radio button
-Var INSTALL_TYPE # Type of installer ("USR" or "SYS")
-
-# Custom includes (depend on above variables so much be here)
-!include "raptorinstallerutils.nsh" # Functions and macros for handling environment variables
-!include "raptorversion.nsh" # Define the RAPTOR_VERSION variable
-
-# Defines
-# !define /date DATE_STAMP "%Y-%m-%d-%H-%M-%S"
-!define INSTALLER_NAME "Raptor v${RAPTOR_VERSION}"
-!define RAPTOR "sbs"
-!define INSTALLER_FILENAME "${RAPTOR}-${RAPTOR_VERSION}.exe"
-!define UNINSTALLER_FILENAME "${RAPTOR}-${RAPTOR_VERSION}-uninstaller.exe"
-
-########################## Attributes ###########################
-# Name of installer executable to create!
-OutFile ${INSTALLER_FILENAME}
-# Name for the installer caption
-Name "Raptor v${RAPTOR_VERSION}"
-
-####################### Generic Behaviour #######################
-# Vista support; use admin in case user decides to install Raptor for all users
-RequestExecutionLevel admin
-# Set XPStyle on
-XPStyle on
-
-###################### Installer Behaviour ######################
-# Warn on Cancel
-!define MUI_ABORTWARNING
-# Abort warning text
-!define MUI_ABORTWARNING_TEXT "Are you sure you want to quit the ${INSTALLER_NAME} installer?"
-# Cancel is default button on cancel dialogue boxes.
-!define MUI_ABORTWARNING_CANCEL_DEFAULT
-# Don't just to final page
-!define MUI_FINISHPAGE_NOAUTOCLOSE
-# Show installer details
-ShowInstDetails show
-
-##################### Pages in the installer #####################
-!insertmacro MUI_PAGE_WELCOME
-# Temporarily useing RELEASE-NOTES.txt as there is not license.txt
-!insertmacro MUI_PAGE_LICENSE ${RAPTOR_LOCATION}\RELEASE-NOTES.txt
-!define MUI_PAGE_HEADER_TEXT "Installation type"
-Page custom UserOrSysInstall UserOrSysInstallLeave
-!define MUI_PAGE_CUSTOMFUNCTION_LEAVE DirLeave # Directory page exit function - disallow spaces in $INSTDIR
-!insertmacro MUI_PAGE_DIRECTORY
-!insertmacro MUI_PAGE_INSTFILES
-!insertmacro MUI_PAGE_FINISH
-
-######################## .onInit function ########################
-Function .onInit
-    StrCpy $INSTDIR "C:\Apps\Raptor"
-FunctionEnd
-
-#################### Sections in the installer ####################
-# "Sections" - i.e. components to install. This installer
-# only has Raptor, so there is no point giving options 
-# to the user.
-Section "Install Raptor" INSTALLRAPTOR
-	
-    StrCpy $SBS_HOME "SBS_HOME"
-	
-    # Install Raptor
-    SetOutPath "$INSTDIR\bin"
-    File /r ${RAPTOR_LOCATION}\bin\*.* 
-    SetOutPath "$INSTDIR\examples"
-    File /r ${RAPTOR_LOCATION}\examples\*.*
-    SetOutPath "$INSTDIR\lib"
-    File /r ${RAPTOR_LOCATION}\lib\*.*
-    SetOutPath "$INSTDIR\python"
-    File /r ${RAPTOR_LOCATION}\python\*.*
-    SetOutPath "$INSTDIR\schema"
-    File /r ${RAPTOR_LOCATION}\schema\*.*
-    SetOutPath "$INSTDIR\win32"
-    File /r ${RAPTOR_LOCATION}\win32\*.*
-    
-    SetOutPath "$INSTDIR"
-    File ${RAPTOR_LOCATION}\RELEASE-NOTES.txt
-    
-    
-    ${Unless} $INSTALL_TYPE == "NO_ENV"
-        # Back up system and user environments before changing them.
-        !insertmacro DefineDateStamp
-        !define SYS_REG_BACKUP_FILE "$INSTDIR\SysEnvBackUpPreInstall-${DATE_STAMP}.reg"
-        !define USR_REG_BACKUP_FILE "$INSTDIR\UsrEnvBackUpPreInstall-${DATE_STAMP}.reg"
-        
-        # Save System Environment just in case.
-        ${registry::SaveKey} "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" "${SYS_REG_BACKUP_FILE}" "" "$RESULT"
-        
-        ${If} $RESULT == 0
-            DetailPrint "Successfully backed up system environment in ${SYS_REG_BACKUP_FILE}."
-        ${Else}
-            DetailPrint "Failed to back up system environment due to an unknown error."
-        ${EndIf}
-        
-        # Save user Environment just in case.
-        ${registry::SaveKey} "HKCU\Environment" "${USR_REG_BACKUP_FILE}" "" "$RESULT"
-        
-        ${If} $RESULT == 0
-            DetailPrint "Successfully backed up user environment in ${USR_REG_BACKUP_FILE}."
-        ${Else}
-            DetailPrint "Failed to back up user environment due to an unknown error."
-        ${EndIf}
-    	
-    	# Reset error flag
-    	ClearErrors
-    	
-    	# Write SBS_HOME variable; if it exists, the user will be asked if they want it to be overwritten.
-    	# Read the env var from the appropriate place
-    	!insertmacro ReadEnvVar $SBS_HOME $RESULT
-    	
-    	${Unless} ${Errors} # No errors, so $SBS_HOME exists
-    		DetailPrint "Env Var $SBS_HOME exists with value $RESULT"
-    		# Ask user if they want it replaced. If yes, write it, if no don't write it.
-    		MessageBox MB_YESNO|MB_ICONQUESTION "The ${INSTALLER_NAME} installer has detected that you already have the SBS_HOME environment variable set with value $RESULT. Would you like the installer to overwrite it with the value $INSTDIR? Click yes to over write with value $INSTDIR, and no to leave it as $RESULT." IDYES write_env_var_yes IDNO write_env_var_no
-    	${Else} # No env var named $SBS_HOME
-    		DetailPrint "Env Var $SBS_HOME does not exist!"
-    	${EndUnless}
-    	
-write_env_var_yes:
-    	# Write SBS_HOME to registry
-    	Push "SBS_HOME" # Third on stack
-    	Push "$INSTDIR" # Second on stack
-    	Push "" # First on stack
-    	
-    	# Needs env var name, env var value, then "" on the stack
-    	call WriteEnvVar
-    	
-    	# Prepend PATH with %SBS_HOME%\bin
-    	Push "%SBS_HOME%\bin" # First on stack
-    	call PrependToPath
-    	goto end
-        
-write_env_var_no:
-    	DetailPrint "Not writing the environment variable $SBS_HOME."
-        
-end:
-    ${EndUnless} 
-	
-	# Generate batch file to set environment variables for Raptor
-	StrCpy $RESULT "@REM Environment variables for ${INSTALLER_NAME}$\r$\nset SBS_HOME=$INSTDIR$\r$\nset PATH=%SBS_HOME%\bin;%PATH%$\r$\n"
-	!insertmacro WriteFile "RaptorEnv.bat" "$RESULT"
-SectionEnd
-
-# Finishing up installation.
-Section
-    ${Unless} $INSTALL_TYPE == "NO_ENV"
-    	# Refresh environment to get changes for SBS_HOME and PATH
-        !insertmacro RefreshEnv
-    ${EndUnless}
-	
-	# Write the uninstaller
-	# WriteUninstaller "$INSTDIR\${UNINSTALLER_FILENAME}"
-	WriteUninstaller "$INSTDIR\${UNINSTALLER_FILENAME}"
-	# Unload registry plug in
-	${registry::Unload}
-SectionEnd
-
-# Custom install page to select install type
-Function UserOrSysInstall
-    !insertmacro MUI_HEADER_TEXT "Choose Installation Type" "Choose the type of installation \
-    you would like for your computer."
-    
-	nsDialogs::Create 1018
-	Pop $DIALOG
-	
-	# Exit is unable to create dialog
-	${If} $DIALOG == error
-		Abort
-	${EndIf}
-	
-	# Create second radio button for system install
-	#${NSD_CreateRadioButton} 0 10u 100% 33% "Install Raptor for all users on this computer. \
-    #(Recommended).$\nThis option modifies system wide environment variables."
-	#Pop $ALLUSERSINSTALL_HWND
-    
-    # Create first radio button for user install
-    #${NSD_CreateRadioButton} 0 45u 100% 67% "Install Raptor just for me on this computer.\
-    #$\nThis option modifies only user environment variables."
-    #Pop $USERONLYINSTALL_HWND
-	
-	# Create first radio button for system install
-	${NSD_CreateRadioButton} 0 0% 100% 30% "Install Raptor for all users on this computer. \
-    (Recommended).$\nThis option modifies system wide environment variables."
-	Pop $ALLUSERSINSTALL_HWND
-    
-    # Create second radio button for user install
-    ${NSD_CreateRadioButton} 0 25% 100% 30% "Install Raptor just for me on this computer.\
-    $\nThis option modifies only user environment variables."
-    Pop $USERONLYINSTALL_HWND
-    
-    # Create third radio button for file-only install
-    ${NSD_CreateRadioButton} 0 50% 100% 40% "Install, but do not modify the environment.\
-    $\nThis option only unpacks Raptor's files. A batch file in the installation \ 
-    folder (RaptorEnv.bat) can be used to set Raptor's environment variables in a command prompt."
-    Pop $NOENVCHANGES_HWND
-	
-	# Update page control with previous state, if set.
-	# Initially these will be blank, so set system install to be on by default.
-	${If} $USERONLYINSTALL_STATE == ""
-	${AndIf} $ALLUSERSINSTALL_STATE == ""
-    ${AndIf} $NOENVCHANGES_STATE == ""
-		${NSD_SetState} $ALLUSERSINSTALL_HWND ${BST_CHECKED}
-	${Else} # Previously set, user has returned to this page using "Back" button
-		${If} $USERONLYINSTALL_STATE == ${BST_CHECKED}
-			${NSD_SetState} $USERONLYINSTALL_HWND ${BST_CHECKED}
-		${ElseIf} $NOENVCHANGES_STATE == ${BST_CHECKED}
-            ${NSD_SetState} $NOENVCHANGES_HWND ${BST_CHECKED}
-        ${Else}
-			${NSD_SetState} $ALLUSERSINSTALL_HWND ${BST_CHECKED}
-		${EndIf}
-	${EndIf}
-	
-	nsDialogs::Show
-FunctionEnd
-
-# Store the states of the radio buttons once the user has left the page.
-Function UserOrSysInstallLeave
-	${NSD_GetState} $USERONLYINSTALL_HWND $USERONLYINSTALL_STATE
-	${NSD_GetState} $ALLUSERSINSTALL_HWND $ALLUSERSINSTALL_STATE
-    ${NSD_GetState} $NOENVCHANGES_HWND $NOENVCHANGES_STATE
-    
-    # Set the ${INSTALL_TYPE} variable
-    ${If} $USERONLYINSTALL_STATE == ${BST_CHECKED}
-        StrCpy $INSTALL_TYPE "USR"
-    ${EndIf}
-    
-    ${If} $ALLUSERSINSTALL_STATE == ${BST_CHECKED}
-        StrCpy $INSTALL_TYPE "SYS"
-    ${EndIf}
-    
-    ${If} $NOENVCHANGES_STATE == ${BST_CHECKED}
-        StrCpy $INSTALL_TYPE "NO_ENV"
-    ${EndIf}
-    
-    ${Unless} $INSTALL_TYPE == "USR"
-    ${AndUnless} $INSTALL_TYPE == "SYS"
-    ${AndUnless} $INSTALL_TYPE == "NO_ENV"
-        Abort "Failed to determine installation type.\n\
-        $$INSTALL_TYPE = $\"$INSTALL_TYPE$\"."
-    ${EndUnless} 
-FunctionEnd
-
-Function DirLeave
-	StrCpy $0 " "
-	${REQuoteMeta} $9 $0 # $9 now contains the meta-quoted version of $0
-	${If} $INSTDIR =~ $9
-		MessageBox MB_OK|MB_ICONSTOP "Please choose a directory without a space in it."
-		Abort
-	${EndIf}
-FunctionEnd
-
-########################### Uninstaller #########################
-######################## .onInit function ########################
-Function un.onInit
-	!undef DATE_STAMP
-	!insertmacro DefineDateStamp
-FunctionEnd
-########################### Behaviour ###########################
-# Warn on Cancel
-!define MUI_UNABORTWARNING
-# Abort warning text
-!undef MUI_UNABORTWARNING_TEXT
-!define MUI_UNABORTWARNING_TEXT "Are you sure you want to quit the ${INSTALLER_NAME} uninstaller?"
-# Cancel is default button on cancel dialogue boxes.
-!define MUI_UNABORTWARNING_CANCEL_DEFAULT
-# Don't just to final page
-!define MUI_UNFINISHPAGE_NOAUTOCLOSE
-# Show uninstaller details
-ShowUninstDetails show
-
-#################### Pages in the uninstaller ####################
-!insertmacro MUI_UNPAGE_WELCOME
-!insertmacro MUI_UNPAGE_CONFIRM
-!insertmacro MUI_UNPAGE_INSTFILES
-!insertmacro MUI_UNPAGE_FINISH
-
-################## Sections in the uninstaller ##################
-# There is only one section in the uninstaller.
-Section "Uninstall"
-    # Delete Raptor
-    RmDir /r $INSTDIR\bin
-    RmDir /r $INSTDIR\examples
-    RmDir /r $INSTDIR\lib
-    RmDir /r $INSTDIR\python
-    RmDir /r $INSTDIR\schema
-    RmDir /r $INSTDIR\win32
-    Delete $INSTDIR\RELEASE-NOTES.txt
-    Delete $INSTDIR\RaptorEnv.bat
-    Delete $INSTDIR\${UNINSTALLER_FILENAME}
-    
-    !undef SYS_REG_BACKUP_FILE
-    !undef USR_REG_BACKUP_FILE
-    !define SYS_REG_BACKUP_FILE "$INSTDIR\SysEnvBackUpPreUninstall-${DATE_STAMP}.reg"
-    !define USR_REG_BACKUP_FILE "$INSTDIR\UsrEnvBackUpPreUninstall-${DATE_STAMP}.reg"
-    
-    # Save System Environment just in case.
-    ${registry::SaveKey} "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" "${SYS_REG_BACKUP_FILE}" "" "$RESULT"
-    
-    ${If} $RESULT == 0
-        DetailPrint "Successfully backed up system environment in ${SYS_REG_BACKUP_FILE}."
-    ${Else}
-        DetailPrint "Failed to back up system environment due to an unknown error."
-    ${EndIf}
-    
-    # Save user Environment just in case.
-    ${registry::SaveKey} "HKCU\Environment" "${USR_REG_BACKUP_FILE}" "" "$RESULT"
-    
-    ${If} $RESULT == 0
-        DetailPrint "Successfully backed up user environment in ${USR_REG_BACKUP_FILE}."
-    ${Else}
-        DetailPrint "Failed to back up user environment due to an unknown error."
-    ${EndIf}
-	
-	# Reset error flag
-	ClearErrors
-	
-	# Read user SBS_HOME
-	!insertmacro ReadUsrEnvVar "SBS_HOME" $RESULT
-	
-	${Unless} ${Errors} # No errors, so user %SBS_HOME% exists
-		DetailPrint "Removing user environment variable SBS_HOME ($RESULT)"
-		
-		# Reset error flag
-		ClearErrors
-		!insertmacro RmUsrEnvVar "SBS_HOME"
-		
-		${If} ${Errors}
-			DetailPrint "ERROR: The ${INSTALLER_NAME} uninstaller could not remove the user environment variable SBS_HOME."
-			DetailPrint "Please remove it manually."
-		${EndIf}
-		
-	${Else} # No env var named $SBS_HOME
-		DetailPrint "Note: Unable to find user environment variable SBS_HOME."
-		DetailPrint "If required, this variable may need to be removed manually."
-	${EndUnless}
-	
-	# Reset error flag
-	ClearErrors
-	
-	# Read system SBS_HOME
-	!insertmacro ReadSysEnvVar "SBS_HOME" $RESULT
-	
-	${Unless} ${Errors} # No errors, so system $SBS_HOME exists
-		DetailPrint "Removing system environment variable SBS_HOME ($RESULT)"
-		
-		# Reset error flag
-		ClearErrors
-		!insertmacro RmSysEnvVar "SBS_HOME"
-		
-		${If} ${Errors}
-			DetailPrint "ERROR: The ${INSTALLER_NAME} uninstaller could not remove the \
-            System environment variable SBS_HOME."
-			DetailPrint "Please remove it manually."
-		${EndIf}
-		
-	${Else} # No env var named $SBS_HOME
-		DetailPrint "Note: Unable to find system environment variable SBS_HOME."
-		DetailPrint "If required, this variable may need to be removed manually."
-	${EndUnless}
-	
-	################################# Clean up the path env vars #################################
-	# Reset error flag
-	ClearErrors
-	
-	# Read user path
-	!insertmacro ReadUsrPath $RESULT
-    DetailPrint "Read user Path: $RESULT"
-	
-	${Unless} ${Errors} # No errors, so user $SBS_HOME exists
-		${If} $RESULT == "" # If it came back empty.
-			DetailPrint "No user Path available - nothing to do."
-		${Else}
-            ${If} $RESULT un.=~ "%SBS_HOME%\\bin;" # Only need to act if %SBS_HOME%\bin; is in the Path
-    			DetailPrint "Removing %SBS_HOME%\bin; from user path"
-    			
-    			# Reset error flag and clean user Path
-    			ClearErrors
-    			!insertmacro RemoveFromPathString $RESULT "%SBS_HOME%\bin;"
-    			
-    			DetailPrint "DEBUG: User path $$RESULT = "
-    	        DetailPrint "DEBUG: User path  $RESULT"
-    			
-    			${If} $RESULT == ""
-    				!insertmacro RmUsrEnvVar "Path"
-    			${Else}
-    				# Write cleaned Path to registry
-    	            !insertmacro WriteUsrEnvVarExp "Path" $RESULT
-    			${EndIf}
-    			
-    			${If} ${Errors}
-    				DetailPrint "ERROR: The ${INSTALLER_NAME} uninstaller could not clean the user Path. Please clean it manually."
-    			${EndIf}
-            ${Else}
-                DetailPrint "Nothing to remove from user path."
-            ${EndIf}
-		${EndIf}
-		
-	${Else} # No user path
-		DetailPrint "Note: Unable to find user Path environment variable."
-		DetailPrint "Please check that the variable exists and remove %SBS_HOME\bin manually if required."
-	${EndUnless}
-    
-    # Read system path
-    !insertmacro ReadSysPath $RESULT
-    DetailPrint "Read system Path: $RESULT"
-    
-    ${Unless} ${Errors} # No errors, so system path read OK.
-        ${If} $RESULT un.=~ "%SBS_HOME%\\bin;" # Only need to act if %SBS_HOME%\bin; is in the Path 
-        
-            DetailPrint "Removing %SBS_HOME%\bin; from system path"
-            
-            # Reset error flag
-            ClearErrors
-            !insertmacro RemoveFromPathString $RESULT "%SBS_HOME%\bin;"
-            DetailPrint "DEBUG: System Path $$RESULT = "
-            DetailPrint "DEBUG: System Path $RESULT"
-            ClearErrors
-            # Write cleaned PATH to registry
-            !insertmacro WriteSysEnvVarExp "Path" $RESULT
-            
-            ${If} ${Errors}
-                DetailPrint "ERROR: The ${INSTALLER_NAME} uninstaller could not clean the PATH."
-                DetailPrint "Please clean it manually."
-            ${EndIf}
-        ${Else}
-            DetailPrint "Nothing to remove from system path."
-        ${EndIf}
-    ${Else} # Some error reading system path
-        DetailPrint "Note: Unable to read the system Path environment variable."
-        DetailPrint "Please check that the variable and remove %SBS_HOME\bin manually if required."
-    ${EndUnless}
-	
-	##########################################################################
-	# Refresh environment to get changes for SBS_HOME and PATH
-    !insertmacro RefreshEnv
-	
-	# Unload registry plug in
-	${registry::Unload}
-SectionEnd
-
-# Languages
-!insertmacro MUI_LANGUAGE "English"
-
-################################################ End ################################################
+# Copyright (c) 2009-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: 
+# Raptor installer/uninstaller script
+
+# Standard NSIS Library includes 
+!include "MUI2.nsh"
+!include "LogicLib.nsh"
+!include "WinMessages.nsh"
+
+# Extra plugin includes
+!include "nsDialogs.nsh"
+!include "Registry.nsh"
+!include "NSISpcre.nsh"
+!include "Time.nsh"
+
+# Define functions from NSISpcre.nsh 
+!insertmacro REMatches
+!insertmacro un.REMatches
+!insertmacro REQuoteMeta
+
+# Variables
+Var DIALOG
+Var RESULT # Generic variable to obtain results, and immediately thrown away after
+Var RESULT2 # Generic variable to obtain results, and immediately thrown away after
+Var SBS_HOME
+Var USERONLYINSTALL_HWND # HWND of radio button control for user-only installation
+Var ALLUSERSINSTALL_HWND # HWND of radio button control for system installation
+Var NOENVCHANGES_HWND    # HWND of radio button control for file-only installation
+Var USERONLYINSTALL_STATE # State of user-only radio button
+Var ALLUSERSINSTALL_STATE # State of system radio button
+Var NOENVCHANGES_STATE # State of file-only installation radio button
+Var INSTALL_TYPE # Type of installer ("USR" or "SYS")
+
+# Custom includes (depend on above variables so much be here)
+!include "raptorinstallerutils.nsh" # Functions and macros for handling environment variables
+# !include "raptorversion.nsh" # Define the RAPTOR_VERSION variable
+
+# Defines
+!define INSTALLER_NAME "Raptor v${RAPTOR_VERSION}"
+!define RAPTOR "sbs"
+!define INSTALLER_FILENAME "${RAPTOR}-${RAPTOR_VERSION}.exe"
+!define UNINSTALLER_FILENAME "${RAPTOR}-${RAPTOR_VERSION}-uninstaller.exe"
+
+########################## Attributes ###########################
+# Name of installer executable to create!
+OutFile ${INSTALLER_FILENAME}
+# Name for the installer caption
+Name "Raptor v${RAPTOR_VERSION}"
+
+####################### Generic Behaviour #######################
+# Vista support; use admin in case user decides to install Raptor for all users
+RequestExecutionLevel admin
+# Set XPStyle on
+XPStyle on
+
+###################### Installer Behaviour ######################
+# Warn on Cancel
+!define MUI_ABORTWARNING
+# Abort warning text
+!define MUI_ABORTWARNING_TEXT "Are you sure you want to quit the ${INSTALLER_NAME} installer?"
+# Cancel is default button on cancel dialogue boxes.
+!define MUI_ABORTWARNING_CANCEL_DEFAULT
+# Don't just to final page
+!define MUI_FINISHPAGE_NOAUTOCLOSE
+# Show installer details
+ShowInstDetails show
+
+##################### Pages in the installer #####################
+!insertmacro MUI_PAGE_WELCOME
+!insertmacro MUI_PAGE_LICENSE ${RAPTOR_LOCATION}\license.txt
+!define MUI_PAGE_HEADER_TEXT "Installation type"
+Page custom UserOrSysInstall UserOrSysInstallLeave
+!define MUI_PAGE_CUSTOMFUNCTION_LEAVE DirLeave # Directory page exit function - disallow spaces in $INSTDIR
+!insertmacro MUI_PAGE_DIRECTORY
+!insertmacro MUI_PAGE_INSTFILES
+!insertmacro MUI_PAGE_FINISH
+
+######################## .onInit function ########################
+Function .onInit
+    StrCpy $INSTDIR "C:\Apps\Raptor"
+FunctionEnd
+
+#################### Sections in the installer ####################
+# "Sections" - i.e. components to install. This installer
+# only has Raptor, so there is no point giving options 
+# to the user.
+Section "Install Raptor" INSTALLRAPTOR
+	
+    StrCpy $SBS_HOME "SBS_HOME"
+	
+    # Install Raptor
+    SetOutPath "$INSTDIR\bin"
+    File /r /x distribution.policy.s60 ${RAPTOR_LOCATION}\bin\*.* 
+    SetOutPath "$INSTDIR\examples"
+    File /r /x distribution.policy.s60 ${RAPTOR_LOCATION}\examples\*.*
+    SetOutPath "$INSTDIR\lib"
+    File /r /x distribution.policy.s60 ${RAPTOR_LOCATION}\lib\*.*
+    SetOutPath "$INSTDIR\python"
+    File /r /x distribution.policy.s60 ${RAPTOR_LOCATION}\python\*.*
+    SetOutPath "$INSTDIR\schema"
+    File /r /x distribution.policy.s60 ${RAPTOR_LOCATION}\schema\*.*
+    SetOutPath "$INSTDIR\win32\bin"
+    File /r /x distribution.policy.s60 ${RAPTOR_LOCATION}\win32\bin\*.*
+    SetOutPath "$INSTDIR\win32\bv"
+    File /r /x distribution.policy.s60 /x .hg ${BV_LOCATION}\*.*
+    SetOutPath "$INSTDIR\win32\cygwin"
+    File /r /x distribution.policy.s60 /x .hg ${CYGWIN_LOCATION}\*.*
+    SetOutPath "$INSTDIR\win32\mingw"
+    File /r /x distribution.policy.s60 /x .hg ${MINGW_LOCATION}\*.*
+    SetOutPath "$INSTDIR\win32\python264"
+    File /r /x distribution.policy.s60 /x .hg ${PYTHON_LOCATION}\*.*
+    
+    SetOutPath "$INSTDIR"
+    File ${RAPTOR_LOCATION}\RELEASE-NOTES.html
+    SetOutPath "$INSTDIR\notes"
+    File /r /x distribution.policy.s60 ${RAPTOR_LOCATION}\notes\*.*
+    
+    
+    ${Unless} $INSTALL_TYPE == "NO_ENV"
+        # Back up system and user environments before changing them.
+        !insertmacro DefineDateStamp
+        !define SYS_REG_BACKUP_FILE "$INSTDIR\SysEnvBackUpPreInstall-${DATE_STAMP}.reg"
+        !define USR_REG_BACKUP_FILE "$INSTDIR\UsrEnvBackUpPreInstall-${DATE_STAMP}.reg"
+        
+        # Save System Environment just in case.
+        ${registry::SaveKey} "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" "${SYS_REG_BACKUP_FILE}" "" "$RESULT"
+        
+        ${If} $RESULT == 0
+            DetailPrint "Successfully backed up system environment in ${SYS_REG_BACKUP_FILE}."
+        ${Else}
+            DetailPrint "Failed to back up system environment due to an unknown error."
+        ${EndIf}
+        
+        # Save user Environment just in case.
+        ${registry::SaveKey} "HKCU\Environment" "${USR_REG_BACKUP_FILE}" "" "$RESULT"
+        
+        ${If} $RESULT == 0
+            DetailPrint "Successfully backed up user environment in ${USR_REG_BACKUP_FILE}."
+        ${Else}
+            DetailPrint "Failed to back up user environment due to an unknown error."
+        ${EndIf}
+    	
+    	# Reset error flag
+    	ClearErrors
+    	
+    	# Write SBS_HOME variable; if it exists, the user will be asked if they want it to be overwritten.
+    	# Read the env var from the appropriate place
+    	!insertmacro ReadEnvVar $SBS_HOME $RESULT
+    	
+    	${Unless} ${Errors} # No errors, so $SBS_HOME exists
+    		DetailPrint "Env Var $SBS_HOME exists with value $RESULT"
+    		# Ask user if they want it replaced. If yes, write it, if no don't write it.
+    		MessageBox MB_YESNO|MB_ICONQUESTION "The ${INSTALLER_NAME} installer has detected that you already have the SBS_HOME environment variable set with value $RESULT. Would you like the installer to overwrite it with the value $INSTDIR? Click yes to over write with value $INSTDIR, and no to leave it as $RESULT." IDYES write_env_var_yes IDNO write_env_var_no
+    	${Else} # No env var named $SBS_HOME
+    		DetailPrint "Env Var $SBS_HOME does not exist!"
+    	${EndUnless}
+    	
+write_env_var_yes:
+    	# Write SBS_HOME to registry
+    	Push "SBS_HOME" # Third on stack
+    	Push "$INSTDIR" # Second on stack
+    	Push "" # First on stack
+    	
+    	# Needs env var name, env var value, then "" on the stack
+    	call WriteEnvVar
+    	
+    	# Prepend PATH with %SBS_HOME%\bin
+    	Push "%SBS_HOME%\bin" # First on stack
+    	call PrependToPath
+    	goto end
+        
+write_env_var_no:
+    	DetailPrint "Not writing the environment variable $SBS_HOME."
+        
+end:
+    ${EndUnless} 
+	
+	# Generate batch file to set environment variables for Raptor
+	StrCpy $RESULT "@REM Environment variables for ${INSTALLER_NAME}$\r$\nset SBS_HOME=$INSTDIR$\r$\nset PATH=%SBS_HOME%\bin;%PATH%$\r$\n"
+	SetOutPath "$INSTDIR"
+	!insertmacro WriteFile "RaptorEnv.bat" "$RESULT"
+SectionEnd
+
+# Finishing up installation.
+Section
+    ${Unless} $INSTALL_TYPE == "NO_ENV"
+    	# Refresh environment to get changes for SBS_HOME and PATH
+        !insertmacro RefreshEnv
+    ${EndUnless}
+	
+	# Write the uninstaller
+	# WriteUninstaller "$INSTDIR\${UNINSTALLER_FILENAME}"
+	WriteUninstaller "$INSTDIR\${UNINSTALLER_FILENAME}"
+	# Unload registry plug in
+	${registry::Unload}
+SectionEnd
+
+# Custom install page to select install type
+Function UserOrSysInstall
+    !insertmacro MUI_HEADER_TEXT "Choose Installation Type" "Choose the type of installation \
+    you would like for your computer."
+    
+	nsDialogs::Create 1018
+	Pop $DIALOG
+	
+	# Exit is unable to create dialog
+	${If} $DIALOG == error
+		Abort
+	${EndIf}
+	
+	# Create second radio button for system install
+	#${NSD_CreateRadioButton} 0 10u 100% 33% "Install Raptor for all users on this computer. \
+    #(Recommended).$\nThis option modifies system wide environment variables."
+	#Pop $ALLUSERSINSTALL_HWND
+    
+    # Create first radio button for user install
+    #${NSD_CreateRadioButton} 0 45u 100% 67% "Install Raptor just for me on this computer.\
+    #$\nThis option modifies only user environment variables."
+    #Pop $USERONLYINSTALL_HWND
+	
+	# Create first radio button for system install
+	${NSD_CreateRadioButton} 0 0% 100% 30% "Install Raptor for all users on this computer. \
+    (Recommended).$\nThis option modifies system wide environment variables."
+	Pop $ALLUSERSINSTALL_HWND
+    
+    # Create second radio button for user install
+    ${NSD_CreateRadioButton} 0 25% 100% 30% "Install Raptor just for me on this computer.\
+    $\nThis option modifies only user environment variables."
+    Pop $USERONLYINSTALL_HWND
+    
+    # Create third radio button for file-only install
+    ${NSD_CreateRadioButton} 0 50% 100% 40% "Install, but do not modify the environment.\
+    $\nThis option only unpacks Raptor's files. A batch file in the installation \ 
+    folder (RaptorEnv.bat) can be used to set Raptor's environment variables in a command prompt."
+    Pop $NOENVCHANGES_HWND
+	
+	# Update page control with previous state, if set.
+	# Initially these will be blank, so set system install to be on by default.
+	${If} $USERONLYINSTALL_STATE == ""
+	${AndIf} $ALLUSERSINSTALL_STATE == ""
+    ${AndIf} $NOENVCHANGES_STATE == ""
+		${NSD_SetState} $ALLUSERSINSTALL_HWND ${BST_CHECKED}
+	${Else} # Previously set, user has returned to this page using "Back" button
+		${If} $USERONLYINSTALL_STATE == ${BST_CHECKED}
+			${NSD_SetState} $USERONLYINSTALL_HWND ${BST_CHECKED}
+		${ElseIf} $NOENVCHANGES_STATE == ${BST_CHECKED}
+            ${NSD_SetState} $NOENVCHANGES_HWND ${BST_CHECKED}
+        ${Else}
+			${NSD_SetState} $ALLUSERSINSTALL_HWND ${BST_CHECKED}
+		${EndIf}
+	${EndIf}
+	
+	nsDialogs::Show
+FunctionEnd
+
+# Store the states of the radio buttons once the user has left the page.
+Function UserOrSysInstallLeave
+	${NSD_GetState} $USERONLYINSTALL_HWND $USERONLYINSTALL_STATE
+	${NSD_GetState} $ALLUSERSINSTALL_HWND $ALLUSERSINSTALL_STATE
+    ${NSD_GetState} $NOENVCHANGES_HWND $NOENVCHANGES_STATE
+    
+    # Set the ${INSTALL_TYPE} variable
+    ${If} $USERONLYINSTALL_STATE == ${BST_CHECKED}
+        StrCpy $INSTALL_TYPE "USR"
+    ${EndIf}
+    
+    ${If} $ALLUSERSINSTALL_STATE == ${BST_CHECKED}
+        StrCpy $INSTALL_TYPE "SYS"
+    ${EndIf}
+    
+    ${If} $NOENVCHANGES_STATE == ${BST_CHECKED}
+        StrCpy $INSTALL_TYPE "NO_ENV"
+    ${EndIf}
+    
+    ${Unless} $INSTALL_TYPE == "USR"
+    ${AndUnless} $INSTALL_TYPE == "SYS"
+    ${AndUnless} $INSTALL_TYPE == "NO_ENV"
+        Abort "Failed to determine installation type.\n\
+        $$INSTALL_TYPE = $\"$INSTALL_TYPE$\"."
+    ${EndUnless} 
+FunctionEnd
+
+Function DirLeave
+	StrCpy $0 " "
+	${REQuoteMeta} $9 $0 # $9 now contains the meta-quoted version of $0
+	${If} $INSTDIR =~ $9
+		MessageBox MB_OK|MB_ICONSTOP "Please choose a directory without a space in it."
+		Abort
+	${EndIf}
+FunctionEnd
+
+########################### Uninstaller #########################
+######################## .onInit function ########################
+Function un.onInit
+	!undef DATE_STAMP
+	!insertmacro DefineDateStamp
+FunctionEnd
+########################### Behaviour ###########################
+# Warn on Cancel
+!define MUI_UNABORTWARNING
+# Abort warning text
+!undef MUI_UNABORTWARNING_TEXT
+!define MUI_UNABORTWARNING_TEXT "Are you sure you want to quit the ${INSTALLER_NAME} uninstaller?"
+# Cancel is default button on cancel dialogue boxes.
+!define MUI_UNABORTWARNING_CANCEL_DEFAULT
+# Don't just to final page
+!define MUI_UNFINISHPAGE_NOAUTOCLOSE
+# Show uninstaller details
+ShowUninstDetails show
+
+#################### Pages in the uninstaller ####################
+!insertmacro MUI_UNPAGE_WELCOME
+!insertmacro MUI_UNPAGE_CONFIRM
+!insertmacro MUI_UNPAGE_INSTFILES
+!insertmacro MUI_UNPAGE_FINISH
+
+################## Sections in the uninstaller ##################
+# There is only one section in the uninstaller.
+Section "Uninstall"
+    # Delete Raptor
+    RmDir /r $INSTDIR\bin
+    RmDir /r $INSTDIR\examples
+    RmDir /r $INSTDIR\lib
+    RmDir /r $INSTDIR\python
+    RmDir /r $INSTDIR\schema
+    RmDir /r $INSTDIR\win32
+    Delete $INSTDIR\RELEASE-NOTES.html
+    RmDir /r $INSTDIR\notes
+    Delete $INSTDIR\RaptorEnv.bat
+    Delete $INSTDIR\${UNINSTALLER_FILENAME}
+    
+    !undef SYS_REG_BACKUP_FILE
+    !undef USR_REG_BACKUP_FILE
+    !define SYS_REG_BACKUP_FILE "$INSTDIR\SysEnvBackUpPreUninstall-${DATE_STAMP}.reg"
+    !define USR_REG_BACKUP_FILE "$INSTDIR\UsrEnvBackUpPreUninstall-${DATE_STAMP}.reg"
+    
+    # Save System Environment just in case.
+    ${registry::SaveKey} "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" "${SYS_REG_BACKUP_FILE}" "" "$RESULT"
+    
+    ${If} $RESULT == 0
+        DetailPrint "Successfully backed up system environment in ${SYS_REG_BACKUP_FILE}."
+    ${Else}
+        DetailPrint "Failed to back up system environment due to an unknown error."
+    ${EndIf}
+    
+    # Save user Environment just in case.
+    ${registry::SaveKey} "HKCU\Environment" "${USR_REG_BACKUP_FILE}" "" "$RESULT"
+    
+    ${If} $RESULT == 0
+        DetailPrint "Successfully backed up user environment in ${USR_REG_BACKUP_FILE}."
+    ${Else}
+        DetailPrint "Failed to back up user environment due to an unknown error."
+    ${EndIf}
+	
+	# Reset error flag
+	ClearErrors
+	
+	# Read user SBS_HOME
+	!insertmacro ReadUsrEnvVar "SBS_HOME" $RESULT
+	
+	${Unless} ${Errors} # No errors, so user %SBS_HOME% exists
+		DetailPrint "Removing user environment variable SBS_HOME ($RESULT)"
+		
+		# Reset error flag
+		ClearErrors
+		!insertmacro RmUsrEnvVar "SBS_HOME"
+		
+		${If} ${Errors}
+			DetailPrint "ERROR: The ${INSTALLER_NAME} uninstaller could not remove the user environment variable SBS_HOME."
+			DetailPrint "Please remove it manually."
+		${EndIf}
+		
+	${Else} # No env var named $SBS_HOME
+		DetailPrint "Note: Unable to find user environment variable SBS_HOME."
+		DetailPrint "If required, this variable may need to be removed manually."
+	${EndUnless}
+	
+	# Reset error flag
+	ClearErrors
+	
+	# Read system SBS_HOME
+	!insertmacro ReadSysEnvVar "SBS_HOME" $RESULT
+	
+	${Unless} ${Errors} # No errors, so system $SBS_HOME exists
+		DetailPrint "Removing system environment variable SBS_HOME ($RESULT)"
+		
+		# Reset error flag
+		ClearErrors
+		!insertmacro RmSysEnvVar "SBS_HOME"
+		
+		${If} ${Errors}
+			DetailPrint "ERROR: The ${INSTALLER_NAME} uninstaller could not remove the \
+            System environment variable SBS_HOME."
+			DetailPrint "Please remove it manually."
+		${EndIf}
+		
+	${Else} # No env var named $SBS_HOME
+		DetailPrint "Note: Unable to find system environment variable SBS_HOME."
+		DetailPrint "If required, this variable may need to be removed manually."
+	${EndUnless}
+	
+	################################# Clean up the path env vars #################################
+	# Reset error flag
+	ClearErrors
+	
+	# Read user path
+	!insertmacro ReadUsrPath $RESULT
+    DetailPrint "Read user Path: $RESULT"
+	
+	${Unless} ${Errors} # No errors, so user $SBS_HOME exists
+		${If} $RESULT == "" # If it came back empty.
+			DetailPrint "No user Path available - nothing to do."
+		${Else}
+            ${If} $RESULT un.=~ "%SBS_HOME%\\bin;" # Only need to act if %SBS_HOME%\bin; is in the Path
+    			DetailPrint "Removing %SBS_HOME%\bin; from user path"
+    			
+    			# Reset error flag and clean user Path
+    			ClearErrors
+    			!insertmacro RemoveFromPathString $RESULT "%SBS_HOME%\bin;"
+    			
+    			DetailPrint "DEBUG: User path $$RESULT = "
+    	        DetailPrint "DEBUG: User path  $RESULT"
+    			
+    			${If} $RESULT == ""
+    				!insertmacro RmUsrEnvVar "Path"
+    			${Else}
+    				# Write cleaned Path to registry
+    	            !insertmacro WriteUsrEnvVarExp "Path" $RESULT
+    			${EndIf}
+    			
+    			${If} ${Errors}
+    				DetailPrint "ERROR: The ${INSTALLER_NAME} uninstaller could not clean the user Path. Please clean it manually."
+    			${EndIf}
+            ${Else}
+                DetailPrint "Nothing to remove from user path."
+            ${EndIf}
+		${EndIf}
+		
+	${Else} # No user path
+		DetailPrint "Note: Unable to find user Path environment variable."
+		DetailPrint "Please check that the variable exists and remove %SBS_HOME\bin manually if required."
+	${EndUnless}
+    
+    # Read system path
+    !insertmacro ReadSysPath $RESULT
+    DetailPrint "Read system Path: $RESULT"
+    
+    ${Unless} ${Errors} # No errors, so system path read OK.
+        ${If} $RESULT un.=~ "%SBS_HOME%\\bin;" # Only need to act if %SBS_HOME%\bin; is in the Path 
+        
+            DetailPrint "Removing %SBS_HOME%\bin; from system path"
+            
+            # Reset error flag
+            ClearErrors
+            !insertmacro RemoveFromPathString $RESULT "%SBS_HOME%\bin;"
+            DetailPrint "DEBUG: System Path $$RESULT = "
+            DetailPrint "DEBUG: System Path $RESULT"
+            ClearErrors
+            # Write cleaned PATH to registry
+            !insertmacro WriteSysEnvVarExp "Path" $RESULT
+            
+            ${If} ${Errors}
+                DetailPrint "ERROR: The ${INSTALLER_NAME} uninstaller could not clean the PATH."
+                DetailPrint "Please clean it manually."
+            ${EndIf}
+        ${Else}
+            DetailPrint "Nothing to remove from system path."
+        ${EndIf}
+    ${Else} # Some error reading system path
+        DetailPrint "Note: Unable to read the system Path environment variable."
+        DetailPrint "Please check that the variable and remove %SBS_HOME\bin manually if required."
+    ${EndUnless}
+	
+	##########################################################################
+	# Refresh environment to get changes for SBS_HOME and PATH
+    !insertmacro RefreshEnv
+	
+	# Unload registry plug in
+	${registry::Unload}
+SectionEnd
+
+# Languages
+!insertmacro MUI_LANGUAGE "English"
+
+################################################ End ################################################
--- a/sbsv2/raptor/util/install-windows/raptorinstallerutils.nsh	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/install-windows/raptorinstallerutils.nsh	Wed Jun 23 16:56:47 2010 +0800
@@ -1,243 +1,243 @@
-# 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: 
-# Raptor installer header file
-
-!include "WordFunc.nsh"
-
-# Time macros
-!macro DefineDateStamp
-	${time::GetLocalTime} $RESULT
-	${time::TimeString} "$RESULT" $0 $1 $2 $3 $4 $5
-	!define DATE_STAMP "$2-$1-$0-$3-$4-$5"
-!macroend
-
-# Env var manipulation macros
-
-# Macro to refresh the computer's environment by sending Windows the
-# WM_WININICHANGE message so that it re-reads the environment changes
-# the installer has made.
-!macro RefreshEnv
-	DetailPrint "Refreshing your computer's environment..."
-	SendMessage ${HWND_BROADCAST} ${WM_WININICHANGE} 0 "STR:Environment" $RESULT /TIMEOUT=5000
-	DetailPrint "Done."
-!macroend
-
-# Sets ${RESULT} to value of user env var named ${VARNAME}
-!macro ReadUsrEnvVar VARNAME RESULT
-	ReadRegStr ${RESULT} HKCU "Environment" ${VARNAME}
-!macroend
-
-# Sets ${RESULT} to value of system env var named ${VARNAME}
-!macro ReadSysEnvVar VARNAME RESULT
-	ReadRegStr ${RESULT} HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment" ${VARNAME}
-!macroend
-
-# Read the env var from the appropriate place
-!macro ReadEnvVar VARNAME RESULT
-	${If} $USERONLYINSTALL_STATE == ${BST_CHECKED}
-		# User env var
-		!insertmacro ReadUsrEnvVar ${VARNAME} ${RESULT}
-	${ElseIf} $ALLUSERSINSTALL_STATE == ${BST_CHECKED}
-		# System env var
-		!insertmacro ReadSysEnvVar ${VARNAME} ${RESULT}
-	${Else}
-		# Something has gone wrong!
-		MessageBox MB_OK|MB_ICONSTOP "Failed to determine installation type (Current User or All Users)."
-	${EndIf}
-!macroend
-
-# Read the user Path
-!macro ReadUsrPath OUTPUT
-	# Reset error flag
-	ClearErrors
-    !insertmacro ReadUsrEnvVar "Path" ${OUTPUT}
-    
-	${If} ${Errors}
-		DetailPrint "User has no Path variable."
-		StrCpy "${OUTPUT}" ""
-	${EndIf}
-!macroend
-
-# Read the user Path
-!macro ReadSysPath OUTPUT
-	# Reset error flag
-	ClearErrors
-	!insertmacro ReadSysEnvVar "Path" ${OUTPUT}
-!macroend
-
-# Read the Path (installer only).
-!macro ReadPath OUTPUT
-${If} $USERONLYINSTALL_STATE == ${BST_CHECKED}
-	# User env var
-	!insertmacro ReadUsrPath ${OUTPUT}
-${ElseIf} $ALLUSERSINSTALL_STATE == ${BST_CHECKED}
-	# System env var
-	!insertmacro ReadSysPath ${OUTPUT}
-${Else}
-	# Something has gone wrong!
-	MessageBox MB_OK|MB_ICONSTOP "Failed to determine installation type (Current User or All Users)."
-${EndIf}
-!macroend
-
-# Writes a string user environment variable to the Registry
-# DO NOT USE FOR WRITING THE PATH ENVIRONMENT VARIABLE. USE THE BELOW MARCOS!
-!macro WriteUsrEnvVar VARNAME VALUE
-	WriteRegStr HKCU "Environment" ${VARNAME} ${VALUE}
-!macroend
-
-# Writes a string system environment variable to the Registry
-# DO NOT USE FOR WRITING THE PATH ENVIRONMENT VARIABLE. USE THE BELOW MARCOS!
-!macro WriteSysEnvVar VARNAME VALUE
-	WriteRegStr HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment" ${VARNAME} ${VALUE}
-!macroend
-
-# Use the following for PATH env var that can expand variables it contains, e.g.
-# Something like 
-# %SBS_HOME%;C:\Windows...
-# should be written to the registry
-# SBS_HOME must NOT be an "expandable string"; in fact expandable strings don't work recursively
-
-# Writes an expandable string user environment variable to the Registry; mostly used for PATH
-!macro WriteUsrEnvVarExp VARNAME VALUE
-	WriteRegExpandStr HKCU "Environment" ${VARNAME} ${VALUE}
-!macroend
-
-# Writes an expandable string system environment variable to the Registry; mostly used for PATH
-!macro WriteSysEnvVarExp VARNAME VALUE
-	WriteRegExpandStr HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment" ${VARNAME} ${VALUE}
-!macroend
-
-# Deletes a user environment variable from the Registry
-!macro RmUsrEnvVar VARNAME
-	DeleteRegValue HKCU "Environment" ${VARNAME}
-!macroend
-
-# Deletes a system environment variable from the Registry
-!macro RmSysEnvVar VARNAME
-	DeleteRegValue HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment" ${VARNAME}
-!macroend
-
-# Push env var name, value of env var, and either "" (for normal string env var) 
-# or "exp" (for expandable env var) onto stack before calling this function
-# in this order
-Function WriteEnvVar
-	pop $2 # Expandable string or not?
-	pop $1 # Env var value
-	pop $0 # Env var name
-		
-	DetailPrint "Going to write evn var $0, with value $1, expandable: $2."
-	
-	# Reset error flag
-	ClearErrors
-	
-	${If} $2 == "exp" # Expandable string env var
-		# Write the env var to the appropriate place
-		${If} $USERONLYINSTALL_STATE == ${BST_CHECKED}
-			DetailPrint "DEBUG $$0 $$1 = $0 $1"
-			# User env var
-			!insertmacro WriteUsrEnvVarExp $0 $1
-		${ElseIf} $ALLUSERSINSTALL_STATE == ${BST_CHECKED}
-			DetailPrint "DEBUG $$0 $$1 = $0 $1"
-			# System env var
-			!insertmacro WriteSysEnvVarExp $0 $1
-		${Else}
-			# Something has gone wrong!
-			MessageBox MB_OK|MB_ICONSTOP "Failed to determine installation type (Current User or All Users)."
-		${EndIf}
-	${Else} # Normal string env var
-		# Write the env var to the appropriate place
-		${If} $USERONLYINSTALL_STATE == ${BST_CHECKED}
-			DetailPrint "DEBUG $$0 $$1 = $0 $1"
-			# User env var
-			!insertmacro WriteUsrEnvVar $0 $1
-		${ElseIf} $ALLUSERSINSTALL_STATE == ${BST_CHECKED}
-			DetailPrint "DEBUG $$0 $$1 = $0 $1"
-			# System env var
-			!insertmacro WriteSysEnvVar $0 $1
-		${Else}
-			# Something has gone wrong!
-			MessageBox MB_OK|MB_ICONSTOP "Failed to determine installation type (Current User or All Users)."
-		${EndIf}
-	${EndIf}
-FunctionEnd
-
-# Prepend the PATH env var with the given string. User/system path is determined using
-# other function.
-Function PrependToPath
-	pop $0 # String to prepend to PATH
-		
-	DetailPrint "Going to prepend PATH with $0."
-	
-	# Reset error flag
-	ClearErrors
-	
-	# Read Path
-	!insertmacro ReadPath $RESULT
-	
-	${Unless} ${Errors} # If no errors
-		${REQuoteMeta} $9 $0 # $9 now contains the meta-quoted version of $0
-		${If} $RESULT !~ $9 # If Path doesn't contain string to add
-			StrLen $RESULT2 "$0;$RESULT"
-			# Warn is Path might be "too" long for the Windows registry.
-			${If} $RESULT2 > 1023
-				DetailPrint "Note: adding %SBS_HOME%\bin; to the start of your Path..."
-				DetailPrint "... will result in a string longer than 1023 characters..."
-				DetailPrint "... being written to your registry. Certain versions of Windows..."
-				DetailPrint "... cannot handle a string that long in the registry. The installer..."
-				DetailPrint "... will continue writing to the registry. However, a back up of..."
-				DetailPrint "... your full environment has been created in your installation directory ..."
-				DetailPrint "... should anything go wrong which can be used to restore your previous Path."
-			${EndIf}
-			
-			Push "Path" # Third on stack
-			Push "$0;$RESULT" # Second on stack
-			Push "exp" # First on stack
-			# Write expandable string to registry
-			call WriteEnvVar
-		${EndIf}
-	${Else}
-		DetailPrint "Error: failed to read Path environment variable."
-	${EndUnless}
-FunctionEnd
-
-# Remove the string STR from the string PATH.
-!macro RemoveFromPathString PATH STR
-	DetailPrint "Going to remove ${STR} from ${PATH}."
-	${WordReplace} "${PATH}" "${STR}" "" "+" $RESULT2
-	DetailPrint "Debug: Replaced ${STR} in RESULT2 = [$RESULT2]"
-	StrCpy ${PATH} "$RESULT2"
-	
-	${WordReplace} "${PATH}" ";;" ";" "+" $RESULT2
-	DetailPrint "Debug: Replaced ;; in RESULT2 = [$RESULT2]"
-	StrCpy ${PATH} $RESULT2
-!macroend
-
-################### Miscellaneous utilities
-# WriteFile - writes a file with given contents
-# FILENAME - full path to file (all directories in path must exist)
-# CONTENTS - string to write to the file.
-!macro WriteFile FILENAME CONTENTS
-	DetailPrint "Creating batch file for setting Raptor's environment..."
-	ClearErrors
-	FileOpen $0 ${FILENAME} w
-	${Unless} ${Errors}
-		FileWrite $0 "${CONTENTS}"
-		FileClose $0
-		DetailPrint "Done."		
-	${Else}
-		DetailPrint "Error: failed to write RaptorEnv.bat."
-	${EndUnless}
-!macroend
-
-################################################ End ################################################
+# 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: 
+# Raptor installer header file
+
+!include "WordFunc.nsh"
+
+# Time macros
+!macro DefineDateStamp
+	${time::GetLocalTime} $RESULT
+	${time::TimeString} "$RESULT" $0 $1 $2 $3 $4 $5
+	!define DATE_STAMP "$2-$1-$0-$3-$4-$5"
+!macroend
+
+# Env var manipulation macros
+
+# Macro to refresh the computer's environment by sending Windows the
+# WM_WININICHANGE message so that it re-reads the environment changes
+# the installer has made.
+!macro RefreshEnv
+	DetailPrint "Refreshing your computer's environment..."
+	SendMessage ${HWND_BROADCAST} ${WM_WININICHANGE} 0 "STR:Environment" $RESULT /TIMEOUT=5000
+	DetailPrint "Done."
+!macroend
+
+# Sets ${RESULT} to value of user env var named ${VARNAME}
+!macro ReadUsrEnvVar VARNAME RESULT
+	ReadRegStr ${RESULT} HKCU "Environment" ${VARNAME}
+!macroend
+
+# Sets ${RESULT} to value of system env var named ${VARNAME}
+!macro ReadSysEnvVar VARNAME RESULT
+	ReadRegStr ${RESULT} HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment" ${VARNAME}
+!macroend
+
+# Read the env var from the appropriate place
+!macro ReadEnvVar VARNAME RESULT
+	${If} $USERONLYINSTALL_STATE == ${BST_CHECKED}
+		# User env var
+		!insertmacro ReadUsrEnvVar ${VARNAME} ${RESULT}
+	${ElseIf} $ALLUSERSINSTALL_STATE == ${BST_CHECKED}
+		# System env var
+		!insertmacro ReadSysEnvVar ${VARNAME} ${RESULT}
+	${Else}
+		# Something has gone wrong!
+		MessageBox MB_OK|MB_ICONSTOP "Failed to determine installation type (Current User or All Users)."
+	${EndIf}
+!macroend
+
+# Read the user Path
+!macro ReadUsrPath OUTPUT
+	# Reset error flag
+	ClearErrors
+    !insertmacro ReadUsrEnvVar "Path" ${OUTPUT}
+    
+	${If} ${Errors}
+		DetailPrint "User has no Path variable."
+		StrCpy "${OUTPUT}" ""
+	${EndIf}
+!macroend
+
+# Read the user Path
+!macro ReadSysPath OUTPUT
+	# Reset error flag
+	ClearErrors
+	!insertmacro ReadSysEnvVar "Path" ${OUTPUT}
+!macroend
+
+# Read the Path (installer only).
+!macro ReadPath OUTPUT
+${If} $USERONLYINSTALL_STATE == ${BST_CHECKED}
+	# User env var
+	!insertmacro ReadUsrPath ${OUTPUT}
+${ElseIf} $ALLUSERSINSTALL_STATE == ${BST_CHECKED}
+	# System env var
+	!insertmacro ReadSysPath ${OUTPUT}
+${Else}
+	# Something has gone wrong!
+	MessageBox MB_OK|MB_ICONSTOP "Failed to determine installation type (Current User or All Users)."
+${EndIf}
+!macroend
+
+# Writes a string user environment variable to the Registry
+# DO NOT USE FOR WRITING THE PATH ENVIRONMENT VARIABLE. USE THE BELOW MARCOS!
+!macro WriteUsrEnvVar VARNAME VALUE
+	WriteRegStr HKCU "Environment" ${VARNAME} ${VALUE}
+!macroend
+
+# Writes a string system environment variable to the Registry
+# DO NOT USE FOR WRITING THE PATH ENVIRONMENT VARIABLE. USE THE BELOW MARCOS!
+!macro WriteSysEnvVar VARNAME VALUE
+	WriteRegStr HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment" ${VARNAME} ${VALUE}
+!macroend
+
+# Use the following for PATH env var that can expand variables it contains, e.g.
+# Something like 
+# %SBS_HOME%;C:\Windows...
+# should be written to the registry
+# SBS_HOME must NOT be an "expandable string"; in fact expandable strings don't work recursively
+
+# Writes an expandable string user environment variable to the Registry; mostly used for PATH
+!macro WriteUsrEnvVarExp VARNAME VALUE
+	WriteRegExpandStr HKCU "Environment" ${VARNAME} ${VALUE}
+!macroend
+
+# Writes an expandable string system environment variable to the Registry; mostly used for PATH
+!macro WriteSysEnvVarExp VARNAME VALUE
+	WriteRegExpandStr HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment" ${VARNAME} ${VALUE}
+!macroend
+
+# Deletes a user environment variable from the Registry
+!macro RmUsrEnvVar VARNAME
+	DeleteRegValue HKCU "Environment" ${VARNAME}
+!macroend
+
+# Deletes a system environment variable from the Registry
+!macro RmSysEnvVar VARNAME
+	DeleteRegValue HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment" ${VARNAME}
+!macroend
+
+# Push env var name, value of env var, and either "" (for normal string env var) 
+# or "exp" (for expandable env var) onto stack before calling this function
+# in this order
+Function WriteEnvVar
+	pop $2 # Expandable string or not?
+	pop $1 # Env var value
+	pop $0 # Env var name
+		
+	DetailPrint "Going to write evn var $0, with value $1, expandable: $2."
+	
+	# Reset error flag
+	ClearErrors
+	
+	${If} $2 == "exp" # Expandable string env var
+		# Write the env var to the appropriate place
+		${If} $USERONLYINSTALL_STATE == ${BST_CHECKED}
+			DetailPrint "DEBUG $$0 $$1 = $0 $1"
+			# User env var
+			!insertmacro WriteUsrEnvVarExp $0 $1
+		${ElseIf} $ALLUSERSINSTALL_STATE == ${BST_CHECKED}
+			DetailPrint "DEBUG $$0 $$1 = $0 $1"
+			# System env var
+			!insertmacro WriteSysEnvVarExp $0 $1
+		${Else}
+			# Something has gone wrong!
+			MessageBox MB_OK|MB_ICONSTOP "Failed to determine installation type (Current User or All Users)."
+		${EndIf}
+	${Else} # Normal string env var
+		# Write the env var to the appropriate place
+		${If} $USERONLYINSTALL_STATE == ${BST_CHECKED}
+			DetailPrint "DEBUG $$0 $$1 = $0 $1"
+			# User env var
+			!insertmacro WriteUsrEnvVar $0 $1
+		${ElseIf} $ALLUSERSINSTALL_STATE == ${BST_CHECKED}
+			DetailPrint "DEBUG $$0 $$1 = $0 $1"
+			# System env var
+			!insertmacro WriteSysEnvVar $0 $1
+		${Else}
+			# Something has gone wrong!
+			MessageBox MB_OK|MB_ICONSTOP "Failed to determine installation type (Current User or All Users)."
+		${EndIf}
+	${EndIf}
+FunctionEnd
+
+# Prepend the PATH env var with the given string. User/system path is determined using
+# other function.
+Function PrependToPath
+	pop $0 # String to prepend to PATH
+		
+	DetailPrint "Going to prepend PATH with $0."
+	
+	# Reset error flag
+	ClearErrors
+	
+	# Read Path
+	!insertmacro ReadPath $RESULT
+	
+	${Unless} ${Errors} # If no errors
+		${REQuoteMeta} $9 $0 # $9 now contains the meta-quoted version of $0
+		${If} $RESULT !~ $9 # If Path doesn't contain string to add
+			StrLen $RESULT2 "$0;$RESULT"
+			# Warn is Path might be "too" long for the Windows registry.
+			${If} $RESULT2 > 1023
+				DetailPrint "Note: adding %SBS_HOME%\bin; to the start of your Path..."
+				DetailPrint "... will result in a string longer than 1023 characters..."
+				DetailPrint "... being written to your registry. Certain versions of Windows..."
+				DetailPrint "... cannot handle a string that long in the registry. The installer..."
+				DetailPrint "... will continue writing to the registry. However, a back up of..."
+				DetailPrint "... your full environment has been created in your installation directory ..."
+				DetailPrint "... should anything go wrong which can be used to restore your previous Path."
+			${EndIf}
+			
+			Push "Path" # Third on stack
+			Push "$0;$RESULT" # Second on stack
+			Push "exp" # First on stack
+			# Write expandable string to registry
+			call WriteEnvVar
+		${EndIf}
+	${Else}
+		DetailPrint "Error: failed to read Path environment variable."
+	${EndUnless}
+FunctionEnd
+
+# Remove the string STR from the string PATH.
+!macro RemoveFromPathString PATH STR
+	DetailPrint "Going to remove ${STR} from ${PATH}."
+	${WordReplace} "${PATH}" "${STR}" "" "+" $RESULT2
+	DetailPrint "Debug: Replaced ${STR} in RESULT2 = [$RESULT2]"
+	StrCpy ${PATH} "$RESULT2"
+	
+	${WordReplace} "${PATH}" ";;" ";" "+" $RESULT2
+	DetailPrint "Debug: Replaced ;; in RESULT2 = [$RESULT2]"
+	StrCpy ${PATH} $RESULT2
+!macroend
+
+################### Miscellaneous utilities
+# WriteFile - writes a file with given contents
+# FILENAME - full path to file (all directories in path must exist)
+# CONTENTS - string to write to the file.
+!macro WriteFile FILENAME CONTENTS
+	DetailPrint "Creating batch file for setting Raptor's environment..."
+	ClearErrors
+	FileOpen $0 ${FILENAME} w
+	${Unless} ${Errors}
+		FileWrite $0 "${CONTENTS}"
+		FileClose $0
+		DetailPrint "Done."		
+	${Else}
+		DetailPrint "Error: failed to write RaptorEnv.bat."
+	${EndUnless}
+!macroend
+
+################################################ End ################################################
--- a/sbsv2/raptor/util/install-windows/unzip.py	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/install-windows/unzip.py	Wed Jun 23 16:56:47 2010 +0800
@@ -1,203 +1,203 @@
-# The MIT License
-# Copyright (c) 2003 Doug Tolton
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-# 
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-# 
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-# THE SOFTWARE.
-#
-#
-
-""" unzip.py
-    Version: 1.1
-
-    Extract a zip file to the directory provided
-    It first creates the directory structure to house the files
-    then it extracts the files to it.
-
-    Sample usage:
-    Windows command line
-    unzip.py -p 10 -z c:\testfile.zip -o c:\testoutput
-    
-    Linux command line
-    unzip.py -p 10 -z /tmp/testfile.zip -o /tmp/testoutput
-
-    Python class:
-    import unzip
-    un = unzip.unzip()
-    un.extract(r'c:\testfile.zip', r'c:\testoutput') # Windows
-    un.extract(r'/tmp/testfile.zip', '/tmp/testoutput') # Linux
-    
-    By Doug Tolton
-    
-    Taken from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252508
-    
-    Updated by Daniel Jacobs to be OS-neutral and more stable.
-"""
-
-import sys
-import zipfile
-import os
-import os.path
-import getopt
-import errno
-
-class unzip:
-    def __init__(self, verbose = False, percent = 10):
-        self.verbose = verbose
-        self.percent = percent
-        
-    def extract(self, file, dir):
-        """ Extract all the files in the zip file, "file" to the directory "dir" with full path names."""
-        if not dir.endswith(':') and not os.path.exists(dir):
-            self._makedir(dir)
-
-        zf = zipfile.ZipFile(file)
-
-        # create directory structure to house files
-        self._createstructure(file, dir)
-
-        num_files = len(zf.namelist())
-        percent = self.percent
-        divisions = 100 / percent
-        perc = int(num_files / divisions)
-
-        # extract files to directory structure
-        for i, name in enumerate(zf.namelist()):
-
-            if self.verbose == True:
-                print "Extracting %s" % name
-            elif perc > 0 and (i % perc) == 0 and i > 0:
-                complete = int (i / perc) * percent
-                print "%s%% complete" % complete
-
-            if not name.endswith('/'):
-                # Normalise the path so that it is correct for the current OS
-                localdirname = os.path.normpath(os.path.join(dir, os.path.dirname(name)))
-                
-                # Ensure that the directory hierarchy that contains the files exists so that 
-                # writing to the file is valid. Note: some zip tools omit directory information 
-                # and this will cause problems when trying to write file to non-existent directories.
-                self._makedir(localdirname)
-                    
-                # Write the file
-                outfile = open(os.path.join(localdirname, os.path.basename(name)), 'wb')
-                outfile.write(zf.read(name))
-                outfile.flush()
-                outfile.close()
-        
-        zf.close()
-
-
-    def _createstructure(self, file, dir):
-        self._makedirs(self._listdirs(file), dir)
-
-
-    def _makedirs(self, directories, basedir):
-        """ Create any directories that don't currently exist """
-        for dir in directories:
-            curdir = os.path.join(basedir, dir)
-            # Normalise path for current OS.
-            curdir = os.path.normpath(curdir)
-            self._makedir(curdir) 
-            
-    
-    def _makedir(self, directory):
-        """ Create a directory "safely", catching the "file exists" exception if the 
-        directory has been created by another process. Creates all parent directories
-        recursively as requied. """
-        if not os.path.exists(directory):
-            # In multi-threaded uses, it is possible that this directory 
-            # has been made in the meantime. Catch this exception.
-            try:
-                os.makedirs(directory)
-            except OSError, aOSError:
-                # If the OSError is that the file exists then we are OK - this
-                # might occur in a multi-threaded or multi-process environment;
-                # otherwise re-raise the exception since it's something else bad.
-                if aOSError.errno != errno.EEXIST:
-                    raise aOSError
-
-    def _listdirs(self, file):
-        """ Grabs all the directories in the zip structure
-        This is necessary to create the structure before trying
-        to extract the file to it. """
-        zf = zipfile.ZipFile(file)
-
-        dirs = []
-
-        for name in zf.namelist():
-            if name.endswith('/'):
-                if self.verbose == True:
-                    print "Directory \"" + name + "\" will be made."
-                dirs.append(name)
-        
-        zf.close()
-        return dirs
-
-def usage():
-    print """usage: unzip.py -z <zipfile> -o <targetdir>
-    <zipfile> is the source zipfile to extract
-    <targetdir> is the target destination
-
-    -z zipfile to extract
-    -o target location
-    -p sets the percentage notification
-    -v sets the extraction to verbose (overrides -p)
-
-    long options also work:
-    --verbose
-    --percent=10
-    --zipfile=<zipfile>
-    --outdir=<targetdir>"""
-    
-
-def main():
-    shortargs = 'vhp:z:o:'
-    longargs = ['verbose', 'help', 'percent=', 'zipfile=', 'outdir=']
-
-    unzipper = unzip()
-
-    try:
-        opts, args = getopt.getopt(sys.argv[1:], shortargs, longargs)
-    except getopt.GetoptError:
-        usage()
-        sys.exit(2)
-
-    zipsource = ""
-    zipdest = ""
-
-    for o, a in opts:
-        if o in ("-v", "--verbose"):
-            unzipper.verbose = True
-        if o in ("-p", "--percent"):
-            if not unzipper.verbose == True:
-                unzipper.percent = int(a)
-        if o in ("-z", "--zipfile"):
-            zipsource = a
-        if o in ("-o", "--outdir"):
-            zipdest = a
-        if o in ("-h", "--help"):
-            usage()
-            sys.exit()
-
-    if zipsource == "" or zipdest == "":
-        usage()
-        sys.exit()
-            
-    unzipper.extract(zipsource, zipdest)
-
-if __name__ == '__main__': main()
+# The MIT License
+# Copyright (c) 2003 Doug Tolton
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+# 
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+# 
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+#
+#
+
+""" unzip.py
+    Version: 1.1
+
+    Extract a zip file to the directory provided
+    It first creates the directory structure to house the files
+    then it extracts the files to it.
+
+    Sample usage:
+    Windows command line
+    unzip.py -p 10 -z c:\testfile.zip -o c:\testoutput
+    
+    Linux command line
+    unzip.py -p 10 -z /tmp/testfile.zip -o /tmp/testoutput
+
+    Python class:
+    import unzip
+    un = unzip.unzip()
+    un.extract(r'c:\testfile.zip', r'c:\testoutput') # Windows
+    un.extract(r'/tmp/testfile.zip', '/tmp/testoutput') # Linux
+    
+    By Doug Tolton
+    
+    Taken from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252508
+    
+    Updated by Daniel Jacobs to be OS-neutral and more stable.
+"""
+
+import sys
+import zipfile
+import os
+import os.path
+import getopt
+import errno
+
+class unzip:
+    def __init__(self, verbose = False, percent = 10):
+        self.verbose = verbose
+        self.percent = percent
+        
+    def extract(self, file, dir):
+        """ Extract all the files in the zip file, "file" to the directory "dir" with full path names."""
+        if not dir.endswith(':') and not os.path.exists(dir):
+            self._makedir(dir)
+
+        zf = zipfile.ZipFile(file)
+
+        # create directory structure to house files
+        self._createstructure(file, dir)
+
+        num_files = len(zf.namelist())
+        percent = self.percent
+        divisions = 100 / percent
+        perc = int(num_files / divisions)
+
+        # extract files to directory structure
+        for i, name in enumerate(zf.namelist()):
+
+            if self.verbose == True:
+                print "Extracting %s" % name
+            elif perc > 0 and (i % perc) == 0 and i > 0:
+                complete = int (i / perc) * percent
+                print "%s%% complete" % complete
+
+            if not name.endswith('/'):
+                # Normalise the path so that it is correct for the current OS
+                localdirname = os.path.normpath(os.path.join(dir, os.path.dirname(name)))
+                
+                # Ensure that the directory hierarchy that contains the files exists so that 
+                # writing to the file is valid. Note: some zip tools omit directory information 
+                # and this will cause problems when trying to write file to non-existent directories.
+                self._makedir(localdirname)
+                    
+                # Write the file
+                outfile = open(os.path.join(localdirname, os.path.basename(name)), 'wb')
+                outfile.write(zf.read(name))
+                outfile.flush()
+                outfile.close()
+        
+        zf.close()
+
+
+    def _createstructure(self, file, dir):
+        self._makedirs(self._listdirs(file), dir)
+
+
+    def _makedirs(self, directories, basedir):
+        """ Create any directories that don't currently exist """
+        for dir in directories:
+            curdir = os.path.join(basedir, dir)
+            # Normalise path for current OS.
+            curdir = os.path.normpath(curdir)
+            self._makedir(curdir) 
+            
+    
+    def _makedir(self, directory):
+        """ Create a directory "safely", catching the "file exists" exception if the 
+        directory has been created by another process. Creates all parent directories
+        recursively as requied. """
+        if not os.path.exists(directory):
+            # In multi-threaded uses, it is possible that this directory 
+            # has been made in the meantime. Catch this exception.
+            try:
+                os.makedirs(directory)
+            except OSError, aOSError:
+                # If the OSError is that the file exists then we are OK - this
+                # might occur in a multi-threaded or multi-process environment;
+                # otherwise re-raise the exception since it's something else bad.
+                if aOSError.errno != errno.EEXIST:
+                    raise aOSError
+
+    def _listdirs(self, file):
+        """ Grabs all the directories in the zip structure
+        This is necessary to create the structure before trying
+        to extract the file to it. """
+        zf = zipfile.ZipFile(file)
+
+        dirs = []
+
+        for name in zf.namelist():
+            if name.endswith('/'):
+                if self.verbose == True:
+                    print "Directory \"" + name + "\" will be made."
+                dirs.append(name)
+        
+        zf.close()
+        return dirs
+
+def usage():
+    print """usage: unzip.py -z <zipfile> -o <targetdir>
+    <zipfile> is the source zipfile to extract
+    <targetdir> is the target destination
+
+    -z zipfile to extract
+    -o target location
+    -p sets the percentage notification
+    -v sets the extraction to verbose (overrides -p)
+
+    long options also work:
+    --verbose
+    --percent=10
+    --zipfile=<zipfile>
+    --outdir=<targetdir>"""
+    
+
+def main():
+    shortargs = 'vhp:z:o:'
+    longargs = ['verbose', 'help', 'percent=', 'zipfile=', 'outdir=']
+
+    unzipper = unzip()
+
+    try:
+        opts, args = getopt.getopt(sys.argv[1:], shortargs, longargs)
+    except getopt.GetoptError:
+        usage()
+        sys.exit(2)
+
+    zipsource = ""
+    zipdest = ""
+
+    for o, a in opts:
+        if o in ("-v", "--verbose"):
+            unzipper.verbose = True
+        if o in ("-p", "--percent"):
+            if not unzipper.verbose == True:
+                unzipper.percent = int(a)
+        if o in ("-z", "--zipfile"):
+            zipsource = a
+        if o in ("-o", "--outdir"):
+            zipdest = a
+        if o in ("-h", "--help"):
+            usage()
+            sys.exit()
+
+    if zipsource == "" or zipdest == "":
+        usage()
+        sys.exit()
+            
+    unzipper.extract(zipsource, zipdest)
+
+if __name__ == '__main__': main()
--- a/sbsv2/raptor/util/make.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/make.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,43 +1,43 @@
-#
-# 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: 
-# Utility makefile 
-#
-
-RAPTOR_MAKE_VER:=3.81
-
-MAKE_SOURCEDIR:=$(OUTPUTPATH)/make-$(RAPTOR_MAKE_VER)
-MAKE_TAR:=$(SBS_HOME)/util/ext/make-$(RAPTOR_MAKE_VER).tar.bz2
-
-
-define b_make
-
-.PHONY:: make
-
-all:: make
-
-make: $(INSTALLROOT)/bin/make
-	
-$(INSTALLROOT)/bin/make: $(MAKE_TAR) 
-	rm -rf $(MAKE_SOURCEDIR) && \
-	cd $(OUTPUTPATH) && \
-	tar -xjf $(MAKE_TAR) && \
-	(  \
-	cd $(MAKE_SOURCEDIR) && \
-	CFLAGS="-O2 $(GCCTUNE)" ./configure --prefix=$(INSTALLROOT) --disable-job-server && \
-	$(MAKE) -j8 && $(MAKE) install \
-	)
-endef
-
-$(eval $(b_make))
+#
+# 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: 
+# Utility makefile 
+#
+
+RAPTOR_MAKE_VER:=3.81
+
+MAKE_SOURCEDIR:=$(OUTPUTPATH)/make-$(RAPTOR_MAKE_VER)
+MAKE_TAR:=$(SBS_HOME)/util/ext/make-$(RAPTOR_MAKE_VER).tar.bz2
+
+
+define b_make
+
+.PHONY:: make
+
+all:: make
+
+make: $(INSTALLROOT)/bin/make
+	
+$(INSTALLROOT)/bin/make: $(MAKE_TAR) 
+	rm -rf $(MAKE_SOURCEDIR) && \
+	cd $(OUTPUTPATH) && \
+	tar -xjf $(MAKE_TAR) && \
+	(  \
+	cd $(MAKE_SOURCEDIR) && \
+	CFLAGS="-O2 $(GCCTUNE)" ./configure --prefix=$(INSTALLROOT) --disable-job-server && \
+	$(MAKE) -j8 && $(MAKE) install \
+	)
+endef
+
+$(eval $(b_make))
--- a/sbsv2/raptor/util/pvm.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/pvm.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,44 +1,44 @@
-#
-# 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: 
-# Utility makefile 
-#
-
-RAPTOR_PVM_VER:=3.4.5
-
-PVM_TAR:=$(SBS_HOME)/util/ext/pvm$(RAPTOR_PVM_VER).tgz
-PVM_SOURCEDIR:=$(INSTALLROOT)/pvm3
-
-define b_pvm
-.PHONY:: pvm
-
-all:: pvm
-
-pvm: $(INSTALLROOT)/pvm3/console/LINUX/pvm
-	
-$(INSTALLROOT)/pvm3/console/LINUX/pvm: $(PVM_TAR) 
-	rm -rf $(PVM_SOURCEDIR) && \
-	cd $(INSTALLROOT) && \
-	tar -xzf $(PVM_TAR) && \
-	(  \
-	cd $(PVM_SOURCEDIR) && \
-	PVM_ROOT=$(PVM_SOURCEDIR) && \
-	PVM_ARCH=LINUX && \
-	PVM_RSH=/usr/bin/ssh && \
-	export PVM_ROOT PVM_RSH PVM_ARCH && \
-	$(MAKE) && $(MAKE) install \
-	)
-endef
-
-$(eval $(b_pvm))
+#
+# 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: 
+# Utility makefile 
+#
+
+RAPTOR_PVM_VER:=3.4.5
+
+PVM_TAR:=$(SBS_HOME)/util/ext/pvm$(RAPTOR_PVM_VER).tgz
+PVM_SOURCEDIR:=$(INSTALLROOT)/pvm3
+
+define b_pvm
+.PHONY:: pvm
+
+all:: pvm
+
+pvm: $(INSTALLROOT)/pvm3/console/LINUX/pvm
+	
+$(INSTALLROOT)/pvm3/console/LINUX/pvm: $(PVM_TAR) 
+	rm -rf $(PVM_SOURCEDIR) && \
+	cd $(INSTALLROOT) && \
+	tar -xzf $(PVM_TAR) && \
+	(  \
+	cd $(PVM_SOURCEDIR) && \
+	PVM_ROOT=$(PVM_SOURCEDIR) && \
+	PVM_ARCH=LINUX && \
+	PVM_RSH=/usr/bin/ssh && \
+	export PVM_ROOT PVM_RSH PVM_ARCH && \
+	$(MAKE) && $(MAKE) install \
+	)
+endef
+
+$(eval $(b_pvm))
--- a/sbsv2/raptor/util/pvmgmake.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/pvmgmake.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,46 +1,46 @@
-#
-# 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: 
-# Utility makefile 
-#
-
-RAPTOR_PVMGMAKE_VER:=0.9.4-rpt
-
-PVMGMAKE_SOURCEDIR:=$(OUTPUTPATH)/pvmgmake-$(RAPTOR_PVMGMAKE_VER)
-PVMGMAKE_TAR:=$(SBS_HOME)/util/ext/pvmgmake-$(RAPTOR_PVMGMAKE_VER).tgz
-
-
-define b_pvmgmake
-.PHONY:: pvmgmake
-
-all:: pvmgmake
-
-pvmgmake: $(INSTALLROOT)/bin/pvmgmake pvm
-	
-$(INSTALLROOT)/bin/pvmgmake: $(PVMGMAKE_TAR) 
-	rm -rf $(PVMGMAKE_SOURCEDIR) && \
-	cd $(OUTPUTPATH) && \
-	tar -xzf $(PVMGMAKE_TAR) && \
-	(  \
-	cd $(PVMGMAKE_SOURCEDIR) && \
-	PVM_ROOT=$(INSTALLROOT)/pvm3 && \
-	PVM_ARCH=LINUX && \
-	PVM_RSH=/usr/bin/ssh && \
-	export PVM_ROOT PVM_RSH PVM_ARCH && \
-	./configure --program-prefix=pvmg --prefix=$(INSTALLROOT) --libexecdir=$$$$PVM_ROOT/bin/LINUX --with-pvm --disable-job-server --enable-case-insensitive-file-system && \
-	$(MAKE) -j8 && $(MAKE) install \
-	)
-endef
-
-$(eval $(b_pvmgmake))
+#
+# 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: 
+# Utility makefile 
+#
+
+RAPTOR_PVMGMAKE_VER:=0.9.4-rpt
+
+PVMGMAKE_SOURCEDIR:=$(OUTPUTPATH)/pvmgmake-$(RAPTOR_PVMGMAKE_VER)
+PVMGMAKE_TAR:=$(SBS_HOME)/util/ext/pvmgmake-$(RAPTOR_PVMGMAKE_VER).tgz
+
+
+define b_pvmgmake
+.PHONY:: pvmgmake
+
+all:: pvmgmake
+
+pvmgmake: $(INSTALLROOT)/bin/pvmgmake pvm
+	
+$(INSTALLROOT)/bin/pvmgmake: $(PVMGMAKE_TAR) 
+	rm -rf $(PVMGMAKE_SOURCEDIR) && \
+	cd $(OUTPUTPATH) && \
+	tar -xzf $(PVMGMAKE_TAR) && \
+	(  \
+	cd $(PVMGMAKE_SOURCEDIR) && \
+	PVM_ROOT=$(INSTALLROOT)/pvm3 && \
+	PVM_ARCH=LINUX && \
+	PVM_RSH=/usr/bin/ssh && \
+	export PVM_ROOT PVM_RSH PVM_ARCH && \
+	./configure --program-prefix=pvmg --prefix=$(INSTALLROOT) --libexecdir=$$$$PVM_ROOT/bin/LINUX --with-pvm --disable-job-server --enable-case-insensitive-file-system && \
+	$(MAKE) -j8 && $(MAKE) install \
+	)
+endef
+
+$(eval $(b_pvmgmake))
--- a/sbsv2/raptor/util/python.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/python.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,45 +1,45 @@
-#
-# 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: 
-# Utility makefile 
-#
-
-# Build Python for Raptor
-
-RAPTOR_PYTHON_VER:=2.6.2
-
-PYTHON_SOURCEDIR:=$(OUTPUTPATH)/Python-$(RAPTOR_PYTHON_VER)
-PYTHON_TAR:=$(SBS_HOME)/util/ext/Python-$(RAPTOR_PYTHON_VER).tgz
-PYINSTALLROOT:=$(INSTALLROOT)/python$(subst .,,$(RAPTOR_PYTHON_VER))
-
-define b_python
-.PHONY:: python
-
-all:: python
-
-python: $(PYINSTALLROOT)/bin/python
-	
-$(PYINSTALLROOT)/bin/python: $(PYTHON_TAR) 
-	rm -rf $(PYTHON_SOURCEDIR) && \
-	cd $(OUTPUTPATH) && \
-	tar -xzf $(PYTHON_TAR) && \
-	(  \
-	cd $(PYTHON_SOURCEDIR) && \
-	CFLAGS="-O3 $(GCCTUNE) -s" ./configure --prefix=$(PYINSTALLROOT) --enable-shared --with-threads && \
-	$(MAKE) -j8 && $(MAKE) install \
-	)
-endef
-
-$(eval $(b_python))
-
+#
+# 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: 
+# Utility makefile 
+#
+
+# Build Python for Raptor
+
+RAPTOR_PYTHON_VER:=2.6.2
+
+PYTHON_SOURCEDIR:=$(OUTPUTPATH)/Python-$(RAPTOR_PYTHON_VER)
+PYTHON_TAR:=$(SBS_HOME)/util/ext/Python-$(RAPTOR_PYTHON_VER).tgz
+PYINSTALLROOT:=$(INSTALLROOT)/python$(subst .,,$(RAPTOR_PYTHON_VER))
+
+define b_python
+.PHONY:: python
+
+all:: python
+
+python: $(PYINSTALLROOT)/bin/python
+	
+$(PYINSTALLROOT)/bin/python: $(PYTHON_TAR) 
+	rm -rf $(PYTHON_SOURCEDIR) && \
+	cd $(OUTPUTPATH) && \
+	tar -xzf $(PYTHON_TAR) && \
+	(  \
+	cd $(PYTHON_SOURCEDIR) && \
+	CFLAGS="-O3 $(GCCTUNE) -s" ./configure --prefix=$(PYINSTALLROOT) --enable-shared --with-threads && \
+	$(MAKE) -j8 && $(MAKE) install \
+	)
+endef
+
+$(eval $(b_python))
+
--- a/sbsv2/raptor/util/ransleep/Makefile	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/ransleep/Makefile	Wed Jun 23 16:56:47 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:
-# Utility makefile 
-#
-#
-
-TARGET:=ransleep
-SOURCES:=$(SBS_HOME:\=/)/util/ransleep/ransleep.c
-
-ifeq ($(filter win,$(HOSTPLATFORM)),win)
-CFLAGS:=-DWIN32
-LDFLAGS:=
-else
-CFLAGS:=
-LDFLAGS:=-lpthread
-endif
-
-$(eval $(cprogram))
+# 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:
+# Utility makefile 
+#
+#
+
+TARGET:=ransleep
+SOURCES:=$(SBS_HOME:\=/)/util/ransleep/ransleep.c
+
+ifeq ($(filter win,$(HOSTPLATFORM)),win)
+CFLAGS:=-DWIN32
+LDFLAGS:=
+else
+CFLAGS:=
+LDFLAGS:=-lpthread
+endif
+
+$(eval $(cprogram))
--- a/sbsv2/raptor/util/ransleep/ransleep.c	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/ransleep/ransleep.c	Wed Jun 23 16:56:47 2010 +0800
@@ -1,82 +1,82 @@
-/*
-* 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: 
-*
-*/
-
-
-
-
-/* 
-   ransleep.c: sleep for some time period specified in milliseconds
-               optionally choose a random time up to the maximum time specified.
-
-   Description: Useful for delays between retries and for perturbing the
-	        start times of tools which might cause resource starvation 
-		if they all execute at exactly the same time.
-*/
-
-#include "../config.h"
-#include <unistd.h>
-#include <stdlib.h>
-#include <stdio.h>
-
-// OS specific headers
-#ifdef HOST_WIN
-#include <windows.h>
-#else
-#include <sys/types.h>
-#include <sys/select.h>
-#endif
-
-int main(int argc, char *argv[])
-{
-
-	srand(getpid());
-	int millisecs=0;
-
-	if (argc != 2)
-	{
-		fprintf(stderr,"Must supply numeric argument - maximum milliseconds to sleep\n");
-		exit(1);
-	}
-
-	millisecs = atoi(argv[1]);
-
-
-	if (millisecs <= 0 )
-	{
-		fprintf(stderr,"Must supply numeric argument > 0 - maximum milliseconds to sleep\n");
-		exit(1);
-	}
-
-
-	millisecs = rand() % millisecs;
-	fprintf(stderr,"random sleep for %d milliseconds\n", millisecs);
-
-	#ifndef HAS_MILLISECONDSLEEP
-	struct timeval wtime;
-	wtime.tv_sec=millisecs/1000;
-	wtime.tv_usec=(millisecs % 1000) * 1000;
-
-	select(0,NULL,NULL,
-                  NULL, &wtime);
-	#else
-	Sleep(millisecs);
-	#endif
-
-	return 0;
-}
-
-
+/*
+* 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: 
+*
+*/
+
+
+
+
+/* 
+   ransleep.c: sleep for some time period specified in milliseconds
+               optionally choose a random time up to the maximum time specified.
+
+   Description: Useful for delays between retries and for perturbing the
+	        start times of tools which might cause resource starvation 
+		if they all execute at exactly the same time.
+*/
+
+#include "../config.h"
+#include <unistd.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+// OS specific headers
+#ifdef HOST_WIN
+#include <windows.h>
+#else
+#include <sys/types.h>
+#include <sys/select.h>
+#endif
+
+int main(int argc, char *argv[])
+{
+
+	srand(getpid());
+	int millisecs=0;
+
+	if (argc != 2)
+	{
+		fprintf(stderr,"Must supply numeric argument - maximum milliseconds to sleep\n");
+		exit(1);
+	}
+
+	millisecs = atoi(argv[1]);
+
+
+	if (millisecs <= 0 )
+	{
+		fprintf(stderr,"Must supply numeric argument > 0 - maximum milliseconds to sleep\n");
+		exit(1);
+	}
+
+
+	millisecs = rand() % millisecs;
+	fprintf(stderr,"random sleep for %d milliseconds\n", millisecs);
+
+	#ifndef HAS_MILLISECONDSLEEP
+	struct timeval wtime;
+	wtime.tv_sec=millisecs/1000;
+	wtime.tv_usec=(millisecs % 1000) * 1000;
+
+	select(0,NULL,NULL,
+                  NULL, &wtime);
+	#else
+	Sleep(millisecs);
+	#endif
+
+	return 0;
+}
+
+
--- a/sbsv2/raptor/util/talon/Makefile	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/Makefile	Wed Jun 23 16:56:47 2010 +0800
@@ -1,61 +1,71 @@
-# 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:
-# Utility makefile 
-#
-#
-
-
-SHELL:=bash
-
-include $(SBS_HOME:\=/)/util/gccprogram.mk
-
-ifeq ($(filter win,$(HOSTPLATFORM)),win)
-PROCESS_C:=process_win.c
-CFLAGS:=-DHOST_WIN
-LDFLAGS:=$(subst \,/,$(SBS_HOME:\=/)\win32\mingw\lib\libiberty.a)
-else
-PROCESS_C:=process.c
-CFLAGS:=-g
-linux_PTHREADLIBS:=-lpthread
-LDFLAGS:=$(linux_PTHREADLIBS) -lrt
-endif
-
-
-SOURCEDIR:=$(subst \,/,$(SBS_HOME))/util/talon
-
-
-# remember how to clean up:
-MANIFEST:=$(SOURCEDIR)/manifest
-
-TARGET:=talon
-SOURCES:=$(addprefix $(SOURCEDIR)/,talon.c buffer.c sema.c log.c $(PROCESS_C))
-#$(info $(cprogram))
-$(eval $(cprogram))
-
-TARGET:=talonctl
-SOURCES:=$(addprefix $(SOURCEDIR)/,talonctl.c sema.c log.c)
-$(eval $(cprogram))
-
-TARGET:=testbuffer
-SOURCES:=$(addprefix $(SOURCEDIR)/,testbuffer.c buffer.c log.c)
-$(eval $(cprogram))
-
-TARGET:=testprocess
-SOURCES:=$(addprefix $(SOURCEDIR)/,testprocess.c buffer.c log.c  $(PROCESS_C))
-$(eval $(cprogram))
-
-TARGET:=talonlock
-SOURCES:=$(addprefix $(SOURCEDIR)/,lock.c sema.c log.c)
-$(eval $(cprogram))
-
+# 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:
+# Utility makefile 
+#
+#
+
+
+SHELL:=bash
+
+include $(SBS_HOME:\=/)/util/gccprogram.mk
+
+ifeq ($(filter win,$(HOSTPLATFORM)),win)
+CHOMP_C:=chomp.c
+PROCESS_C:=process_win.c
+CFLAGS:=-DHOST_WIN
+ifeq ($(SBS_MINGW),)
+LDFLAGS:=$(subst \,/,$(SBS_HOME:\=/)\win32\mingw\lib\libiberty.a)
+else
+LDFLAGS:=$(subst \,/,$(SBS_MINGW:\=/)\lib\libiberty.a)
+endif
+LDFLAGS:=$(LDFLAGS) -Wl,-lws2_32
+else
+CHOMP_C:=
+PROCESS_C:=process.c
+CFLAGS:=-g
+linux_PTHREADLIBS:=-lpthread
+LDFLAGS:=$(linux_PTHREADLIBS) -lrt
+endif
+
+
+SOURCEDIR:=$(subst \,/,$(SBS_HOME))/util/talon
+
+
+# remember how to clean up:
+MANIFEST:=$(SOURCEDIR)/manifest
+
+TARGET:=talon
+SOURCES:=$(addprefix $(SOURCEDIR)/,talon.c buffer.c sema.c log.c $(PROCESS_C) $(CHOMP_C)) 
+$(eval $(cprogram))
+
+TARGET:=talonctl
+SOURCES:=$(addprefix $(SOURCEDIR)/,talonctl.c sema.c log.c)
+$(eval $(cprogram))
+
+TARGET:=testbuffer
+SOURCES:=$(addprefix $(SOURCEDIR)/,testbuffer.c buffer.c log.c)
+$(eval $(cprogram))
+
+TARGET:=testprocess
+SOURCES:=$(addprefix $(SOURCEDIR)/,testprocess.c buffer.c log.c  $(PROCESS_C))
+$(eval $(cprogram))
+
+TARGET:=talonlock
+SOURCES:=$(addprefix $(SOURCEDIR)/,lock.c sema.c log.c)
+$(eval $(cprogram))
+
+TARGET:=testchomp
+SOURCES:=$(addprefix $(SOURCEDIR)/,testchomp.c chomp.c log.c)
+$(eval $(cprogram))
+
--- a/sbsv2/raptor/util/talon/buffer.c	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/buffer.c	Wed Jun 23 16:56:47 2010 +0800
@@ -1,205 +1,205 @@
-/*
-* 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: 
-* Expanding text buffer
-*
-*/
-
-
-
-
-#include <malloc.h>
-#include "buffer.h"
-#include <string.h>
-
-/* efficient allocation unit: */
-#define ALLOCSIZE 4096
-#define INITIALBLOCKCOUNT 128
-
-byteblock *buffer_newblock(buffer *b, unsigned int size)
-{
-	byteblock *bb;
-	if (!b)
-		return NULL;
-	
-	b->lastblock++;
-	
-	if (b->lastblock == b->maxblocks)
-	{
-		byteblock **nbb = (byteblock **)realloc(b->blocks, sizeof(byteblock *) * (b->maxblocks + INITIALBLOCKCOUNT));
-		if (!nbb)
-			return NULL;
-
-		b->blocks = nbb;
-		b->maxblocks += INITIALBLOCKCOUNT;
-	}
-
-	bb = malloc(sizeof(byteblock) + size-1);
-
-	if (!bb)
-	{
-		
-		return NULL;
-	}
-	
-	b->blocks[b->lastblock] = bb;
-
-	bb->fill = 0;
-	bb->size = size;
-
-	return bb;
-}
-
-buffer *buffer_new(void)
-{
-	buffer *b = malloc(sizeof(buffer));
-
-	if (b)
-	{
-		b->lastblock = -1; /* no blocks as yet */
-		b->maxblocks = INITIALBLOCKCOUNT;
-		b->blocks = (byteblock **)malloc(sizeof(byteblock *) * b->maxblocks);
-		if (!b->blocks)
-		{
-			free(b);
-			return NULL;
-		}
-
-		buffer_newblock(b, ALLOCSIZE);
-	}
-	
-	return b;
-}
-
-
-char *buffer_append(buffer *b, char *bytes, unsigned int size)
-{
-	if (!b || !bytes) 
-		return NULL;
-
-	char *space = buffer_makespace(b, size);
-	if (!space)
-		return NULL;
-	memcpy(space, bytes, size);
-	buffer_usespace(b, size);
-
-	return space;
-}
-
-char *buffer_prepend(buffer *b, char *bytes, unsigned int size)
-{
-	byteblock *bb;
-
-	if (!b || !bytes) 
-		return NULL;
-	
-    	bb = buffer_newblock(b, size);
-	/* cheat by moving the new block from the end to the start. */
-
-	bb = b->blocks[b->lastblock];
-	if (b->lastblock != 0)
-	{
-		memmove(b->blocks+1, b->blocks, sizeof(byteblock *) * b->lastblock );
-		b->blocks[0] = bb;
-	}
-
-	memcpy(&(b->blocks[0]->byte0), bytes, size);
-
-	b->blocks[0]->fill = size;
-
-	return &(b->blocks[0]->byte0);
-}
-
-/* Allocate memory at the end of the buffer (if there isn't
- * enough already) so that the user can append at least that 
- * many bytes without overrunning the buffer.  This is useful
- * where one may not know in advance how many bytes are to be
- * added (e.g. reading from a socket) but one does know the 
- * upper limit.
- */
-char *buffer_makespace(buffer *b, unsigned int size)
-{
-	byteblock *bb;
-	byteblock *last;
-	if (!b)
-		return NULL;
-
-	last = b->blocks[b->lastblock];
-
-	if (last->size - last->fill > size)
-		return (&last->byte0 + last->fill);
-
-	if (size > ALLOCSIZE)
-	{
-       		bb = buffer_newblock(b, size);
-	} else {
-       		bb = buffer_newblock(b, ALLOCSIZE);
-	}
-	
-	if (!bb) 
-		return NULL;
-
-	return &bb->byte0;
-}
-
-void buffer_usespace(buffer *b, unsigned int nbytes)
-{
-	byteblock *last;
-      
-       	if (!b)
-		return;	
-
-	last = b->blocks[b->lastblock];
-
-	if (last->fill + nbytes < last->size)
-		last->fill += nbytes;
-	else
-		last->fill = last->size; /* really an error - no exceptions though. */
-}
-
-byteblock *buffer_getbytes(buffer *b, int *iterator)
-{
-	if (!b)
-		return NULL;
-
-	if (*iterator > b->lastblock)
-		return NULL;
-
-	return b->blocks[(*iterator)++];
-}
-
-void buffer_free(buffer **b)
-{
-	int i;
-	buffer *bf;
-
-	if (!b || !*b)
-		return;
-
-	bf=*b;
-
-	if (bf->blocks)
-	{
-		for (i=0; i <= bf->lastblock; i++)
-		{
-			if (bf->blocks[i])
-				free(bf->blocks[i]);
-		}
-		free(bf->blocks);
-	}
-	free(bf);
-
-	*b = NULL;
-}
-
+/*
+* 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: 
+* Expanding text buffer
+*
+*/
+
+
+
+
+#include <malloc.h>
+#include "buffer.h"
+#include <string.h>
+
+/* efficient allocation unit: */
+#define ALLOCSIZE 4096
+#define INITIALBLOCKCOUNT 128
+
+byteblock *buffer_newblock(buffer *b, unsigned int size)
+{
+	byteblock *bb;
+	if (!b)
+		return NULL;
+	
+	b->lastblock++;
+	
+	if (b->lastblock == b->maxblocks)
+	{
+		byteblock **nbb = (byteblock **)realloc(b->blocks, sizeof(byteblock *) * (b->maxblocks + INITIALBLOCKCOUNT));
+		if (!nbb)
+			return NULL;
+
+		b->blocks = nbb;
+		b->maxblocks += INITIALBLOCKCOUNT;
+	}
+
+	bb = malloc(sizeof(byteblock) + size-1);
+
+	if (!bb)
+	{
+		
+		return NULL;
+	}
+	
+	b->blocks[b->lastblock] = bb;
+
+	bb->fill = 0;
+	bb->size = size;
+
+	return bb;
+}
+
+buffer *buffer_new(void)
+{
+	buffer *b = malloc(sizeof(buffer));
+
+	if (b)
+	{
+		b->lastblock = -1; /* no blocks as yet */
+		b->maxblocks = INITIALBLOCKCOUNT;
+		b->blocks = (byteblock **)malloc(sizeof(byteblock *) * b->maxblocks);
+		if (!b->blocks)
+		{
+			free(b);
+			return NULL;
+		}
+
+		buffer_newblock(b, ALLOCSIZE);
+	}
+	
+	return b;
+}
+
+
+char *buffer_append(buffer *b, char *bytes, unsigned int size)
+{
+	if (!b || !bytes) 
+		return NULL;
+
+	char *space = buffer_makespace(b, size);
+	if (!space)
+		return NULL;
+	memcpy(space, bytes, size);
+	buffer_usespace(b, size);
+
+	return space;
+}
+
+char *buffer_prepend(buffer *b, char *bytes, unsigned int size)
+{
+	byteblock *bb;
+
+	if (!b || !bytes) 
+		return NULL;
+	
+    	bb = buffer_newblock(b, size);
+	/* cheat by moving the new block from the end to the start. */
+
+	bb = b->blocks[b->lastblock];
+	if (b->lastblock != 0)
+	{
+		memmove(b->blocks+1, b->blocks, sizeof(byteblock *) * b->lastblock );
+		b->blocks[0] = bb;
+	}
+
+	memcpy(&(b->blocks[0]->byte0), bytes, size);
+
+	b->blocks[0]->fill = size;
+
+	return &(b->blocks[0]->byte0);
+}
+
+/* Allocate memory at the end of the buffer (if there isn't
+ * enough already) so that the user can append at least that 
+ * many bytes without overrunning the buffer.  This is useful
+ * where one may not know in advance how many bytes are to be
+ * added (e.g. reading from a socket) but one does know the 
+ * upper limit.
+ */
+char *buffer_makespace(buffer *b, unsigned int size)
+{
+	byteblock *bb;
+	byteblock *last;
+	if (!b)
+		return NULL;
+
+	last = b->blocks[b->lastblock];
+
+	if (last->size - last->fill > size)
+		return (&last->byte0 + last->fill);
+
+	if (size > ALLOCSIZE)
+	{
+       		bb = buffer_newblock(b, size);
+	} else {
+       		bb = buffer_newblock(b, ALLOCSIZE);
+	}
+	
+	if (!bb) 
+		return NULL;
+
+	return &bb->byte0;
+}
+
+void buffer_usespace(buffer *b, unsigned int nbytes)
+{
+	byteblock *last;
+      
+       	if (!b)
+		return;	
+
+	last = b->blocks[b->lastblock];
+
+	if (last->fill + nbytes < last->size)
+		last->fill += nbytes;
+	else
+		last->fill = last->size; /* really an error - no exceptions though. */
+}
+
+byteblock *buffer_getbytes(buffer *b, int *iterator)
+{
+	if (!b)
+		return NULL;
+
+	if (*iterator > b->lastblock)
+		return NULL;
+
+	return b->blocks[(*iterator)++];
+}
+
+void buffer_free(buffer **b)
+{
+	int i;
+	buffer *bf;
+
+	if (!b || !*b)
+		return;
+
+	bf=*b;
+
+	if (bf->blocks)
+	{
+		for (i=0; i <= bf->lastblock; i++)
+		{
+			if (bf->blocks[i])
+				free(bf->blocks[i]);
+		}
+		free(bf->blocks);
+	}
+	free(bf);
+
+	*b = NULL;
+}
+
--- a/sbsv2/raptor/util/talon/buffer.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/buffer.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,48 +1,48 @@
-/*
-* 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: 
-* buffer.c
-* Resizable buffer for output from subprocesses.
-*
-*/
-
-
-
-
-#ifndef _TALON_BUFFER_H_
-#define _TALON_BUFFER_H_
-
-
-typedef struct {
-	unsigned int size, fill;
-	/* This struct will be followed by the number of bytes in "size" */
-	char byte0;
-} byteblock;
-
-typedef struct {
-	byteblock **blocks;
-	int maxblocks;
-	int lastblock;
-	unsigned int size;
-} buffer;
-
-buffer *buffer_new(void);
-char *buffer_append(buffer *b, char *bytes, unsigned int size);
-char *buffer_prepend(buffer *b, char *bytes, unsigned int size);
-char *buffer_makespace(buffer *b, unsigned int size);
-void buffer_usespace(buffer *b, unsigned int nbytes);
-byteblock *buffer_getbytes(buffer *b, int *iterator);
-void buffer_free(buffer **b);
-
-#endif
+/*
+* 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: 
+* buffer.c
+* Resizable buffer for output from subprocesses.
+*
+*/
+
+
+
+
+#ifndef _TALON_BUFFER_H_
+#define _TALON_BUFFER_H_
+
+
+typedef struct {
+	unsigned int size, fill;
+	/* This struct will be followed by the number of bytes in "size" */
+	char byte0;
+} byteblock;
+
+typedef struct {
+	byteblock **blocks;
+	int maxblocks;
+	int lastblock;
+	unsigned int size;
+} buffer;
+
+buffer *buffer_new(void);
+char *buffer_append(buffer *b, char *bytes, unsigned int size);
+char *buffer_prepend(buffer *b, char *bytes, unsigned int size);
+char *buffer_makespace(buffer *b, unsigned int size);
+void buffer_usespace(buffer *b, unsigned int nbytes);
+byteblock *buffer_getbytes(buffer *b, int *iterator);
+void buffer_free(buffer **b);
+
+#endif
--- a/sbsv2/raptor/util/talon/lock.c	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/lock.c	Wed Jun 23 16:56:47 2010 +0800
@@ -1,140 +1,140 @@
-/*
-* 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: 
-*
-*/
-
-
-
-
-#include <stdlib.h>
-#include <unistd.h>
-#include <string.h>
-#include <stdio.h>
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <stdarg.h>
-
-#include "sema.h"
-#include "buffer.h"
-#include "../config.h"
-
-/* The output semaphore. */
-sbs_semaphore talon_sem;
-
-#define TALON_ATTEMPT_STRMAX 32
-#define RECIPETAG_STRMAX 2048
-#define STATUS_STRMAX 100
-
-#define TALONDELIMITER '|'
-#define VARNAMEMAX 100
-#define VARVALMAX 1024
-
-
-#include "log.h"
-
-#ifdef HAS_MSVCRT
-/* Make all output handling binary */
-unsigned int _CRT_fmode = _O_BINARY;
-#endif
-
-double getseconds(void)
-{
-	struct timeval tp;
-	gettimeofday(&tp, NULL);
-
-	return (double)tp.tv_sec + ((double)tp.tv_usec)/1000000.0L;
-}
-
-void talon_setenv(char name[], char val[])
-{
-#if defined(HAS_GETENVIRONMENTVARIABLE)
-	SetEnvironmentVariableA(name,val); 
-#elif defined(HAS_GETENV)
-	setenv(name,val, 1);
-#else
-#	error "Need a function for setting environment variables"
-#endif
-}
-
-
-#define TALON_MAXENV 4096
-char * talon_getenv(char name[])
-{
-#if defined(HAS_SETENV)
-	char *val = getenv(name);
-	char *dest = NULL;
-	
-	if (val)
-	{
-		dest = malloc(strlen(val) + 1);
-		if (dest)
-		{
-			strcpy(dest,val);
-		}
-	}
-	return dest;
-#elif defined(HAS_SETENVIRONMENTVARIABLE)
-	char *val = malloc(TALON_MAXENV);
-	if (0 != GetEnvironmentVariableA(name,val,TALON_MAXENV-1))
-		return val;
-	else
-		return NULL;
-#else
-#	error "Need a function for setting environment variables"
-#endif
-}
-
-
-
-int main(int argc, char *argv[])
-{
-	/* find the argument to -c then strip the talon related front section */
-
-	char *recipe = NULL;
-	int talon_returncode = 0;
-
-	/* Now take settings from the environment (having potentially modified it) */	
-	if (talon_getenv("TALON_DEBUG"))
-		loglevel=LOGDEBUG;
-	
-
-	int enverrors = 0;
-
-	char *buildid = talon_getenv("TALON_BUILDID");
-	if (!buildid)
-	{
-		error("error: %s", "TALON_BUILDID not set in environment\n");
-		enverrors++;	
-	}
-
-        talon_sem.name = buildid;
-        talon_sem.timeout = 999999990;
-
-
-	
-
-	int x;
-	debug("debug: %s", "WAITING ON SEMAPHORE\n");
-	x = sema_wait(&talon_sem);
-	if (x == 0)
-	{
-		debug("debug: %s", "SEMAPHORE OBTAINED\n");
-		getchar();
-		sema_release(&talon_sem);
-		debug("debug: %s", "SEMAPHORE RELEASED\n");
-	}
-}
+/*
+* 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: 
+* Test program for grabbing and releasing the talon output semaphore.
+*/
+
+
+
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include <stdio.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <stdarg.h>
+
+#include "sema.h"
+#include "buffer.h"
+#include "../config.h"
+
+/* The output semaphore. */
+sbs_semaphore talon_sem;
+
+#define TALON_ATTEMPT_STRMAX 32
+#define RECIPETAG_STRMAX 2048
+#define STATUS_STRMAX 100
+
+#define TALONDELIMITER '|'
+#define VARNAMEMAX 100
+#define VARVALMAX 1024
+
+
+#include "log.h"
+
+#ifdef HAS_MSVCRT
+/* Make all output handling binary */
+unsigned int _CRT_fmode = _O_BINARY;
+#endif
+
+double getseconds(void)
+{
+	struct timeval tp;
+	gettimeofday(&tp, NULL);
+
+	return (double)tp.tv_sec + ((double)tp.tv_usec)/1000000.0L;
+}
+
+void talon_setenv(char name[], char val[])
+{
+#if defined(HAS_GETENVIRONMENTVARIABLE)
+	SetEnvironmentVariableA(name,val); 
+#elif defined(HAS_GETENV)
+	setenv(name,val, 1);
+#else
+#	error "Need a function for setting environment variables"
+#endif
+}
+
+
+#define TALON_MAXENV 4096
+char * talon_getenv(char name[])
+{
+#if defined(HAS_SETENV)
+	char *val = getenv(name);
+	char *dest = NULL;
+	
+	if (val)
+	{
+		dest = malloc(strlen(val) + 1);
+		if (dest)
+		{
+			strcpy(dest,val);
+		}
+	}
+	return dest;
+#elif defined(HAS_SETENVIRONMENTVARIABLE)
+	char *val = malloc(TALON_MAXENV);
+	if (0 != GetEnvironmentVariableA(name,val,TALON_MAXENV-1))
+		return val;
+	else
+		return NULL;
+#else
+#	error "Need a function for setting environment variables"
+#endif
+}
+
+
+
+int main(int argc, char *argv[])
+{
+	/* find the argument to -c then strip the talon related front section */
+
+	char *recipe = NULL;
+	int talon_returncode = 0;
+
+	/* Now take settings from the environment (having potentially modified it) */	
+	if (talon_getenv("TALON_DEBUG"))
+		loglevel=LOGDEBUG;
+	
+
+	int enverrors = 0;
+
+	char *buildid = talon_getenv("TALON_BUILDID");
+	if (!buildid)
+	{
+		error("error: %s", "TALON_BUILDID not set in environment\n");
+		enverrors++;	
+	}
+
+        talon_sem.name = buildid;
+        talon_sem.timeout = 999999990;
+
+
+	
+
+	int x;
+	debug("debug: %s", "WAITING ON SEMAPHORE\n");
+	x = sema_wait(&talon_sem);
+	if (x == 0)
+	{
+		debug("debug: %s", "SEMAPHORE OBTAINED\n");
+		getchar();
+		sema_release(&talon_sem);
+		debug("debug: %s", "SEMAPHORE RELEASED\n");
+	}
+}
--- a/sbsv2/raptor/util/talon/log.c	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/log.c	Wed Jun 23 16:56:47 2010 +0800
@@ -1,57 +1,57 @@
-/*
-* 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: 
-*
-*/
-
-
-
-
-#include "log.h"
-#include <stdarg.h>
-#include <stdio.h>
-
-int loglevel=LOGNORMAL;
-int debug(const char *format, ...)
-{
-	int rt=0;
-	
-	if (loglevel >= LOGDEBUG)
-	{
-		va_list ap;
-		va_start(ap, format);
-		rt = vfprintf(stderr, format,  ap);
-		va_end(ap);
-
-	}
-
-	return rt;
-}
-
-
-int error(const char *format, ...)
-{
-	int rt=0;
-	
-	if (loglevel >= LOGNORMAL)
-	{
-		va_list ap;
-		va_start(ap, format);
-		rt = vfprintf(stderr, format,  ap);
-		va_end(ap);
-
-	}
-
-	return rt;
-}
+/*
+* 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: 
+*
+*/
+
+
+
+
+#include "log.h"
+#include <stdarg.h>
+#include <stdio.h>
+
+int loglevel=LOGNORMAL;
+int debug(const char *format, ...)
+{
+	int rt=0;
+	
+	if (loglevel >= LOGDEBUG)
+	{
+		va_list ap;
+		va_start(ap, format);
+		rt = vfprintf(stderr, format,  ap);
+		va_end(ap);
+
+	}
+
+	return rt;
+}
+
+
+int error(const char *format, ...)
+{
+	int rt=0;
+	
+	if (loglevel >= LOGNORMAL)
+	{
+		va_list ap;
+		va_start(ap, format);
+		rt = vfprintf(stderr, format,  ap);
+		va_end(ap);
+
+	}
+
+	return rt;
+}
--- a/sbsv2/raptor/util/talon/log.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/log.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,34 +1,34 @@
-/*
-* 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: 
-*
-*/
-
-
-
-
-#ifndef _TALONLOG_H_
-#define _TALONLOG_H_
-
-#define LOGNONE 0
-#define LOGNORMAL 0
-#define LOGDEBUG 1
-#define DEBUG(xxx) debug xxx
-
-extern int loglevel;
-
-int debug(const char *format, ...);
-int error(const char *format, ...);
-
-#endif
+/*
+* 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: 
+*
+*/
+
+
+
+
+#ifndef _TALONLOG_H_
+#define _TALONLOG_H_
+
+#define LOGNONE 0
+#define LOGNORMAL 0
+#define LOGDEBUG 1
+#define DEBUG(xxx) debug xxx
+
+extern int loglevel;
+
+int debug(const char *format, ...);
+int error(const char *format, ...);
+
+#endif
--- a/sbsv2/raptor/util/talon/process.c	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/process.c	Wed Jun 23 16:56:47 2010 +0800
@@ -1,203 +1,207 @@
-/*
-* 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: 
-*
-*/
-
-
-
-
-#include <unistd.h>
-
-#include "process.h"
-#include "buffer.h"
-#include <stdlib.h>
-#include <string.h>
-#include <poll.h>
-#include <signal.h>
-#include <errno.h>
-#include <sys/wait.h>
-
-#include "log.h"
-
-
-proc *process_new(void)
-{
-	proc *p = malloc(sizeof(proc));
-	p->output = buffer_new();
-	if (!p->output)
-	{
-		free(p);
-		return  NULL;
-	}
-	p->starttime = 0;
-	p->endtime = 0;
-	p->returncode = 1;
-	p->pid = 0;
-	p->causeofdeath = PROC_NORMALDEATH;
-
-	return p;
-}
-
-void childsig(int sig)
-{
-	//wait(&stat_loc);
-	DEBUG(("SIGCHLD\n"));
-}
-
-struct sigaction child_action;
-
-proc *process_run(char executable[], char *args[], int timeout)
-{
-	proc *p = process_new();
-
-	if (p == NULL)
-		return NULL;
-
-	char *text;
-	int status;
-	int stdout_p[2];
-	int stderr_p[2];
-
-	child_action.sa_handler = childsig;
-	sigemptyset (&child_action.sa_mask);
-	child_action.sa_flags = 0;
-	sigaction (SIGCHLD, &child_action, NULL);
-	
-	pipe(stdout_p);
-	pipe(stderr_p);
-
-	pid_t child = fork();
-	if (child == 0)
-	{
-		close(stdout_p[0]);
-		dup2(stdout_p[1], 1);
-		close(stdout_p[1]);
-		
-		close(stderr_p[0]);
-		dup2(stderr_p[1], 2);
-		close(stderr_p[1]);
-
-		execvp(executable, args);
-		exit(1);
-	} else if (child == -1) {
-		p->causeofdeath = PROC_SOMEODDDEATH;
-		return p;
-	}
-	else
-	{
-		close(stdout_p[1]);
-		close(stderr_p[1]);
-		p->pid = child;
-		DEBUG(("child running\n"));
-	}
-
-	struct pollfd pf[2];
-
-	int pv;
-	int have_status = 0;
-	do
-	{
-		pf[0].fd = stdout_p[0];
-		pf[1].fd = stderr_p[0];
-		pf[0].events = POLLIN;
-		pf[0].revents = 0;
-		pf[1].events = POLLIN;
-		pf[1].revents = 0;
-		DEBUG(("polling\n"));
-	       	pv = poll(pf, 2, timeout);
-		DEBUG(("polled %d\n", pv));
-		if (pv == -1)
-		{
-		       	if (errno == EAGAIN)
-			{
-				errno = 0;
-				DEBUG(("errno: \n"));
-				continue;
-			} else {
-				/* EINVAL - can't poll */
-				process_free(&p);
-				return NULL;
-			}
-		} else if (pv == 0 ) {
-			/* timeout */
-			DEBUG(("timeout: \n"));
-			kill(p->pid, SIGTERM);
-			p->causeofdeath = PROC_TIMEOUTDEATH;
-			break;
-		}
-		
-		if (pf[0].revents & POLLIN )
-		{
-			char *space = buffer_makespace(p->output, 1024);
-			int nbytes = read(pf[0].fd, space, 1024);
-			if (nbytes < 0)
-				break;
-			buffer_usespace(p->output, nbytes);
-		}
-		if (pf[1].revents & POLLIN )
-		{
-			char *space = buffer_makespace(p->output, 1024);
-			int nbytes = read(pf[1].fd, space, 1024);
-			if (nbytes < 0)
-				break;
-			buffer_usespace(p->output, nbytes);
-		}
-		if  (pf[0].revents & (POLLERR | POLLHUP | POLLNVAL))
-		{
-			DEBUG(("stdout: pollerr %d\n", pf[0].revents));
-			break;
-		}
-		
-		if (  pf[1].revents & (POLLERR | POLLHUP | POLLNVAL)) 
-		{
-			DEBUG(("stderr: pollerr %d\n", pf[1].revents));
-			break;
-		}
-		DEBUG(("events: %d %d \n", pf[0].revents, pf[1].revents));
-	}
-	while (1);
-
-	waitpid(p->pid, &status, 0);
-	if (WIFEXITED(status))
-	{
-		p->causeofdeath = PROC_NORMALDEATH;
-		p->returncode = WEXITSTATUS(status);
-		DEBUG(("process exited normally \n"));
-	} else {
-		p->causeofdeath = PROC_SOMEODDDEATH;
-		if (WIFSIGNALED(status))
-			p->returncode = WTERMSIG(status);
-		else
-			p->returncode = 128;
-		DEBUG(("process terminated \n"));
-	}
-	
-	return p;
-}
-
-void process_free(proc **pp)
-{
-	if (!pp)
-		return;
-	if (! *pp)
-		return;
-
-	if ((*pp)->output)
-		buffer_free(&((*pp)->output));
-	
-	free(*pp);
-
-	*pp = NULL;
-}
+/*
+* Copyright (c) 2009-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 <unistd.h>
+
+#include "process.h"
+#include "buffer.h"
+#include <stdlib.h>
+#include <string.h>
+#include <poll.h>
+#include <signal.h>
+#include <errno.h>
+#include <sys/wait.h>
+
+#include "log.h"
+
+
+proc *process_new(void)
+{
+	proc *p = malloc(sizeof(proc));
+	p->output = buffer_new();
+	if (!p->output)
+	{
+		free(p);
+		return  NULL;
+	}
+	p->starttime = 0;
+	p->endtime = 0;
+	p->returncode = 1;
+	p->pid = 0;
+	p->causeofdeath = PROC_NORMALDEATH;
+
+	return p;
+}
+
+void childsig(int sig)
+{
+	//wait(&stat_loc);
+	DEBUG(("SIGCHLD\n"));
+}
+
+struct sigaction child_action;
+
+proc *process_run(char executable[], char *args[], int timeout)
+{
+	proc *p = process_new();
+
+	if (p == NULL)
+		return NULL;
+
+	char *text;
+	int status;
+	int stdout_p[2];
+	int stderr_p[2];
+
+	child_action.sa_handler = childsig;
+	sigemptyset (&child_action.sa_mask);
+	child_action.sa_flags = 0;
+	sigaction (SIGCHLD, &child_action, NULL);
+	
+	pipe(stdout_p);
+	pipe(stderr_p);
+
+	pid_t child = fork();
+	if (child == 0)
+	{
+		close(stdout_p[0]);
+		dup2(stdout_p[1], 1);
+		close(stdout_p[1]);
+		
+		close(stderr_p[0]);
+		dup2(stderr_p[1], 2);
+		close(stderr_p[1]);
+
+		execvp(executable, args);
+		exit(1);
+	} else if (child == -1) {
+		p->causeofdeath = PROC_SOMEODDDEATH;
+		return p;
+	}
+	else
+	{
+		close(stdout_p[1]);
+		close(stderr_p[1]);
+		p->pid = child;
+		DEBUG(("child running\n"));
+	}
+
+	struct pollfd pf[2];
+
+	int pv;
+	int have_status = 0;
+	do
+	{
+		pf[0].fd = stdout_p[0];
+		pf[1].fd = stderr_p[0];
+		pf[0].events = POLLIN;
+		pf[0].revents = 0;
+		pf[1].events = POLLIN;
+		pf[1].revents = 0;
+		DEBUG(("polling\n"));
+	       	pv = poll(pf, 2, timeout);
+		DEBUG(("polled %d\n", pv));
+		if (pv == -1)
+		{
+		       	if (errno == EAGAIN)
+			{
+				errno = 0;
+				DEBUG(("errno: \n"));
+				continue;
+			} else {
+				/* EINVAL - can't poll */
+				process_free(&p);
+				return NULL;
+			}
+		} else if (pv == 0 ) {
+			/* timeout */
+			DEBUG(("timeout: \n"));
+			kill(p->pid, SIGTERM);
+			p->causeofdeath = PROC_TIMEOUTDEATH;
+			break;
+		}
+		
+		if (pf[0].revents & POLLIN )
+		{
+			char *space = buffer_makespace(p->output, 1024);
+			int nbytes = read(pf[0].fd, space, 1024);
+			if (nbytes < 0)
+				break;
+			buffer_usespace(p->output, nbytes);
+		}
+		if (pf[1].revents & POLLIN )
+		{
+			char *space = buffer_makespace(p->output, 1024);
+			int nbytes = read(pf[1].fd, space, 1024);
+			if (nbytes < 0)
+				break;
+			buffer_usespace(p->output, nbytes);
+		}
+		if  (pf[0].revents & (POLLERR | POLLHUP | POLLNVAL))
+		{
+			DEBUG(("stdout: pollerr %d\n", pf[0].revents));
+			break;
+		}
+		
+		if (  pf[1].revents & (POLLERR | POLLHUP | POLLNVAL)) 
+		{
+			DEBUG(("stderr: pollerr %d\n", pf[1].revents));
+			break;
+		}
+		DEBUG(("events: %d %d \n", pf[0].revents, pf[1].revents));
+	}
+	while (1);
+
+	waitpid(p->pid, &status, 0);
+	if (WIFEXITED(status))
+	{
+		p->causeofdeath = PROC_NORMALDEATH;
+		p->returncode = WEXITSTATUS(status);
+		DEBUG(("process exited normally \n"));
+	} else {
+		if (p->causeofdeath == PROC_TIMEOUTDEATH)
+			p->returncode = 128;
+		else {	
+			p->causeofdeath = PROC_SOMEODDDEATH;
+			if (WIFSIGNALED(status))
+				p->returncode = WTERMSIG(status);
+			else
+				p->returncode = 128;
+		}
+		DEBUG(("process terminated \n"));
+	}
+	
+	return p;
+}
+
+void process_free(proc **pp)
+{
+	if (!pp)
+		return;
+	if (! *pp)
+		return;
+
+	if ((*pp)->output)
+		buffer_free(&((*pp)->output));
+	
+	free(*pp);
+
+	*pp = NULL;
+}
--- a/sbsv2/raptor/util/talon/process.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/process.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,54 +1,54 @@
-/*
-* 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: 
-*
-*/
-
-
-
-
-/*
- * Process.h
- */
-
-
-#ifndef _TALONPROCESS_H_
-#define _TALONPROCESS_H_
-
-#include <sys/types.h>
-#include "buffer.h"
-
-typedef pid_t proc_handle;
-
-#define PROC_NORMALDEATH 0
-#define PROC_TIMEOUTDEATH 1
-#define PROC_SOMEODDDEATH 2
-#define PROC_PIPECREATE 3
-#define PROC_STARTPROC 4
-
-
-typedef struct 
-{
-	proc_handle pid;
-	unsigned int starttime;
-	unsigned int endtime;
-	int returncode;
-	unsigned int causeofdeath;
-	buffer *output;
-} proc;
-
-proc *process_run(char executable[], char *args[], int timeout);
-void process_free(proc **pp);
-	
-#endif
+/*
+* 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: 
+*
+*/
+
+
+
+
+/*
+ * Process.h
+ */
+
+
+#ifndef _TALONPROCESS_H_
+#define _TALONPROCESS_H_
+
+#include <sys/types.h>
+#include "buffer.h"
+
+typedef pid_t proc_handle;
+
+#define PROC_NORMALDEATH 0
+#define PROC_TIMEOUTDEATH 1
+#define PROC_SOMEODDDEATH 2
+#define PROC_PIPECREATE 3
+#define PROC_STARTPROC 4
+
+
+typedef struct 
+{
+	proc_handle pid;
+	unsigned int starttime;
+	unsigned int endtime;
+	int returncode;
+	unsigned int causeofdeath;
+	buffer *output;
+} proc;
+
+proc *process_run(char executable[], char *args[], int timeout);
+void process_free(proc **pp);
+	
+#endif
--- a/sbsv2/raptor/util/talon/process_win.c	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/process_win.c	Wed Jun 23 16:56:47 2010 +0800
@@ -1,406 +1,406 @@
-/*
-* 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: 
-*
-*/
-
-
-
-#include <unistd.h>
-
-#include "talon_process.h"
-#include "buffer.h"
-#include <errno.h>
-
-#include <windows.h> 
-#include <tchar.h>
-#include <stdio.h> 
-//#include <strsafe.h>
-
-
-#include "log.h"
-
-#define RETURN(x) { retval=x; goto cleanup; }
-#define CLEANUP() cleanup:
-
-#define READSIZE 4096
-
-typedef struct ReadOpStruct {
-	HANDLE semaphore;
-	HANDLE thread;
-	DWORD timeout;
-	DWORD error;
-	HANDLE file;
-	BOOL success;
-	char *space;
-	DWORD nbytes;
-	int id;
-	struct ReadOpStruct *next;
-} ReadOp;
-
-typedef struct {
-	ReadOp *first;
-	ReadOp *last;
-	HANDLE semaphore;
-} ReadOpQ;
-
-proc *process_new(void)
-{
-	proc *p = malloc(sizeof(proc));
-	p->output = buffer_new();
-	if (!p->output)
-	{
-		free(p);
-		return  NULL;
-	}
-	p->starttime = 0;
-	p->endtime = 0;
-	p->returncode = 1;
-	p->pid = 0;
-	p->causeofdeath = PROC_NORMALDEATH;
-
-	return p;
-}
-
-#define TALONMAXERRSTR 1024
-
-void printlasterror(void)
-{
-	LPTSTR msg;
-	DWORD err = GetLastError();
-	char buf[1024];
-
-	msg=buf;
-	
-	DEBUG(("error %d\n",err));
-	FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
-	  FORMAT_MESSAGE_FROM_SYSTEM |
-	  FORMAT_MESSAGE_IGNORE_INSERTS, 
-	  NULL, 		// lpSource
-	  err, 	// dwMessageId,
-	  0,
-	  //MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), 			// dwLanguageId,
-	  msg,
-	  0,
-	  NULL
-	);
-
-	DEBUG(("%s\n",msg));
-	//LocalFree(msg);
-}
-
-typedef struct 
-{
-	HANDLE read, write;
-} tl_stream;
-
-
-/* Because windows is d**b, there is no way to avoid blocking on an anonymous
- * pipe.  We can't use CancelIO  to stop reads since that's only in newer
- * versions of Win***ws.  So what we are left with is putting the read operation
- * into a thread, timing out in the main body and ignoring this thread if we
- * feel we have to.
- * */
-
-
-DWORD readpipe_thread(void *param)
-{
-	ReadOpQ *io_ops = (ReadOpQ *)param;
-	ReadOp *iopipe_op;
-	/* have our own buffer since we don't want to risk that the
-	 * caller's buffer might have disappeared by the time
-	 * our readfile unblocks.
-	 */
-
-	while (1)
-	{
-		DWORD  waitres = WaitForSingleObject(io_ops->semaphore, INFINITE);
-		iopipe_op = io_ops->last;
-
-		DEBUG(("readpipe_thread: pre-ReadFile%d: %d \n", iopipe_op->id, iopipe_op->nbytes));
-		iopipe_op->success = ReadFile(iopipe_op->file, iopipe_op->space, iopipe_op->nbytes, &iopipe_op->nbytes, NULL);
-		iopipe_op->error = GetLastError();
-		
-		DEBUG(("readpipe_thread: post-ReadFile%d: %d read, err %d\n", iopipe_op->id, iopipe_op->nbytes,iopipe_op->error));
-		ReleaseSemaphore(iopipe_op->semaphore, 1, NULL);
-	}
-}
-
-proc *process_run(char executable[], char *args[], int timeout)
-{
-	proc *retval = NULL;
-	char *text;
-	int status;
-	tl_stream stdout_p;
-	tl_stream stdin_p;
-	SECURITY_ATTRIBUTES saAttr; 
-	PROCESS_INFORMATION pi;
-	STARTUPINFO si;
-	BOOL createproc_success = FALSE; 
-	BOOL timedout = FALSE; 
-	TCHAR *commandline = NULL;
-
-	proc *p = process_new();
-
-	if (p == NULL)
-		return NULL;
-
-	/* Make sure pipe handles are inherited */
-	saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
-	saAttr.bInheritHandle = TRUE; 
-	saAttr.lpSecurityDescriptor = NULL; 
-	
-	p->causeofdeath = PROC_PIPECREATE;
-
-	DEBUG(("making pipes \n"));
-	/* Child's Stdout */
-	if ( ! CreatePipe(&stdout_p.read, &stdout_p.write, &saAttr, 1) ) 
-	{
-		printlasterror();
-		RETURN(p);
-	}
-	DEBUG(("stdout done \n"));
-	
-	/* read handle to the pipe for STDOUT is not inherited */
-	if ( ! SetHandleInformation(stdout_p.read, HANDLE_FLAG_INHERIT, 0) )
-	{
-		printlasterror();
-		RETURN(p); 
-	}
-	DEBUG(("stdout noinherit \n"));
-	
-	/* a pipe for the child process's STDIN */
-	if ( ! CreatePipe(&stdin_p.read, &stdin_p.write, &saAttr, 0) ) 
-	{
-		printlasterror();
-		RETURN(p); 
-	}
-	DEBUG(("stdin done \n"));
-	
-	/*  write handle to the pipe for STDIN not inherited */
-	if ( ! SetHandleInformation(stdin_p.read, HANDLE_FLAG_INHERIT, 0) )
-	{
-		printlasterror();
-		RETURN(p); 
-	}
-	DEBUG(("pipes done \n"));
-	
-	
-	p->causeofdeath = PROC_START;
-
-	ZeroMemory( &si, sizeof(STARTUPINFO) );
-	ZeroMemory( &pi, sizeof(PROCESS_INFORMATION) );
-	
-	si.cb = sizeof(STARTUPINFO); 
-	si.hStdError = stdout_p.write;
-	si.hStdOutput = stdout_p.write;
-	/*
-	  Rather than use the stdin pipe, which would be
-       		  si.hStdInput = stdin_p.read;
-	  Pass on talon's own standard input to the child process
-	  This helps with programs like xcopy which demand that
-	  they are attached to a console and not just any type of
-	  input file.
-	 */
-	si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
-	si.dwFlags |= STARTF_USESTDHANDLES;
-
-	
-	DEBUG(("pre commandline \n"));
-	/* create the commandline string */
-	int len = 0;
-	int i = 0;
-	while (args[i] != NULL)
-	{
-		len += strlen(args[i++]) + 1;
-	}
-	len+=2;
-
-	commandline = malloc(len*2);
-	if (! commandline) 
-		RETURN(p);
-	commandline[0] = '\0';
-
-	i = 0;
-	while (args[i] != NULL)
-	{
-		strcat(commandline, args[i]);
-		strcat(commandline, " ");
-		i++;
-	}
-
-
-	/* Get the read thread ready to go before creating
-	 * the process.
-	 */
-	ReadOpQ *ropq  = malloc(sizeof(ReadOpQ));
-
-	ropq->first=NULL;
-	ropq->last=NULL;
-	ropq->semaphore = CreateSemaphore(NULL, 0, 1, NULL);
-	DEBUG(("Creating read thread. \n"));
-
-	DWORD readpipe_threadid;
-	HANDLE h_readpipe_thread = CreateThread(NULL, 8192, (LPTHREAD_START_ROUTINE) readpipe_thread, (void*)ropq, 0, &readpipe_threadid);
-
-	/* ready to run the process */
- 
-	DEBUG(("process commandline:\n%s \n", commandline));
-	DEBUG(("\n"));
-	createproc_success = CreateProcess(executable, 
-	   commandline,     // command line 
-	   NULL,          // process security attributes 
-	   NULL,          // primary thread security attributes 
-	   TRUE,          // handles are inherited 
-	   0,             // creation flags 
-	   NULL,          // use parent's environment 
-	   NULL,          // use parent's current directory 
-	   &si,  // STARTUPINFO pointer 
-	   &pi);  // receives PROCESS_INFORMATION 
-
-	if (! createproc_success)
-	{
-		DEBUG(("Createprocess failed. \n"));
-		p->causeofdeath = PROC_SOMEODDDEATH;
-		RETURN(p);
-	}
-
-	int have_status = 0;
-
-
-	DEBUG(("Closing Handles. \n"));
-	if (!CloseHandle(stdout_p.write)) 
-		RETURN(p);
-	if (!CloseHandle(stdin_p.read)) 
-		RETURN(p);
-
-	DEBUG(("Closed Handles. \n"));
-
-
-	static int id=0;
-	do
-	{
-		char *space = buffer_makespace(p->output, READSIZE);
-
-		DWORD waitres;
-		ReadOp *iopipe_op = malloc(sizeof(ReadOp));
-		iopipe_op->semaphore = CreateSemaphore(NULL, 0, 1, NULL);
-		iopipe_op->thread =  h_readpipe_thread;
-		iopipe_op->timeout = timeout;
-		iopipe_op->file = stdout_p.read;
-		iopipe_op->space = malloc(READSIZE);
-		iopipe_op->id = id++;
-		iopipe_op->nbytes = READSIZE;
-		iopipe_op->next = NULL;
-
-		if (!ropq->first)
-		{
-			ropq->first = iopipe_op;
-			ropq->last = iopipe_op;
-		} else {
-			ropq->last->next = iopipe_op;
-			ropq->last = iopipe_op;
-		}
-
-		ReleaseSemaphore(ropq->semaphore, 1, NULL);
-
-		DEBUG(("waiting for read %d\n", timeout));
-		waitres = WaitForSingleObject(iopipe_op->semaphore, timeout);
-		DEBUG(("read wait finished result= %d\n", waitres));
-
-		if (waitres != WAIT_OBJECT_0)
-		{
-			DEBUG(("timeout \n"));
-			timedout = TRUE;
-			break;
-		}
-		else
-		{
-			DEBUG(("read signalled: nbytes: %d \n", iopipe_op->nbytes));
-			if (iopipe_op->nbytes <= 0)
-			{
-				break;
-			}
-			memcpy(space, iopipe_op->space, iopipe_op->nbytes);	
-			buffer_usespace(p->output, iopipe_op->nbytes);	
-			DEBUG(("buffer took on nbytes: %d \n", iopipe_op->nbytes));
-		}
-	}
-	while (1);
-
-	if (timedout == FALSE) 
-	{
-		DEBUG(("Wait for process exit\n"));
-		// Wait until child process exits.
-		WaitForSingleObject(pi.hProcess, INFINITE);
-		DEBUG(("Process exited\n"));
-
-		DWORD exitcode;
-
-		if (GetExitCodeProcess(pi.hProcess, &exitcode))
-		{
-			p->causeofdeath = PROC_NORMALDEATH;
-			p->returncode = exitcode;
-			DEBUG(("process exited normally = %d:\n", p->returncode));
-			RETURN(p);	
-		} else {
-			p->causeofdeath = PROC_SOMEODDDEATH;
-			p->returncode = 128;
-			DEBUG(("process terminated \n"));
-			RETURN(p);	
-		}
-	} else {
-		TerminateProcess(pi.hProcess,1);
-		p->causeofdeath = PROC_TIMEOUTDEATH;
-		p->returncode = 128;
-		DEBUG(("process timedout \n"));
-		RETURN(p);	
-	}
-
-	/* Clean up the read operation queue 
-	ReadOp *r = ropq.first;
-	do
-	{
-		CloseHandle(r->semaphore);
-		free(r->space);
-		free(r);
-		r = r->next;
-	} while (r != NULL); */
-
-	CLEANUP();
-	if (retval == NULL)
-	{
-		if (p)
-			process_free(&p);
-	}
-	if (commandline)
-		free(commandline);
-	
-	return retval;
-}
-
-void process_free(proc **pp)
-{
-	if (!pp)
-		return;
-	if (! *pp)
-		return;
-
-	if ((*pp)->output)
-		buffer_free(&((*pp)->output));
-	
-	free(*pp);
-
-	*pp = NULL;
-}
+/*
+* 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: 
+*
+*/
+
+
+
+#include <unistd.h>
+
+#include "talon_process.h"
+#include "buffer.h"
+#include <errno.h>
+
+#include <windows.h> 
+#include <tchar.h>
+#include <stdio.h> 
+//#include <strsafe.h>
+
+
+#include "log.h"
+
+#define RETURN(x) { retval=x; goto cleanup; }
+#define CLEANUP() cleanup:
+
+#define READSIZE 4096
+
+typedef struct ReadOpStruct {
+	HANDLE semaphore;
+	HANDLE thread;
+	DWORD timeout;
+	DWORD error;
+	HANDLE file;
+	BOOL success;
+	char *space;
+	DWORD nbytes;
+	int id;
+	struct ReadOpStruct *next;
+} ReadOp;
+
+typedef struct {
+	ReadOp *first;
+	ReadOp *last;
+	HANDLE semaphore;
+} ReadOpQ;
+
+proc *process_new(void)
+{
+	proc *p = malloc(sizeof(proc));
+	p->output = buffer_new();
+	if (!p->output)
+	{
+		free(p);
+		return  NULL;
+	}
+	p->starttime = 0;
+	p->endtime = 0;
+	p->returncode = 1;
+	p->pid = 0;
+	p->causeofdeath = PROC_NORMALDEATH;
+
+	return p;
+}
+
+#define TALONMAXERRSTR 1024
+
+void printlasterror(void)
+{
+	LPTSTR msg;
+	DWORD err = GetLastError();
+	char buf[1024];
+
+	msg=buf;
+	
+	DEBUG(("error %d\n",err));
+	FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
+	  FORMAT_MESSAGE_FROM_SYSTEM |
+	  FORMAT_MESSAGE_IGNORE_INSERTS, 
+	  NULL, 		// lpSource
+	  err, 	// dwMessageId,
+	  0,
+	  //MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), 			// dwLanguageId,
+	  msg,
+	  0,
+	  NULL
+	);
+
+	DEBUG(("%s\n",msg));
+	//LocalFree(msg);
+}
+
+typedef struct 
+{
+	HANDLE read, write;
+} tl_stream;
+
+
+/* Because windows is d**b, there is no way to avoid blocking on an anonymous
+ * pipe.  We can't use CancelIO  to stop reads since that's only in newer
+ * versions of Win***ws.  So what we are left with is putting the read operation
+ * into a thread, timing out in the main body and ignoring this thread if we
+ * feel we have to.
+ * */
+
+
+DWORD readpipe_thread(void *param)
+{
+	ReadOpQ *io_ops = (ReadOpQ *)param;
+	ReadOp *iopipe_op;
+	/* have our own buffer since we don't want to risk that the
+	 * caller's buffer might have disappeared by the time
+	 * our readfile unblocks.
+	 */
+
+	while (1)
+	{
+		DWORD  waitres = WaitForSingleObject(io_ops->semaphore, INFINITE);
+		iopipe_op = io_ops->last;
+
+		DEBUG(("readpipe_thread: pre-ReadFile%d: %d \n", iopipe_op->id, iopipe_op->nbytes));
+		iopipe_op->success = ReadFile(iopipe_op->file, iopipe_op->space, iopipe_op->nbytes, &iopipe_op->nbytes, NULL);
+		iopipe_op->error = GetLastError();
+		
+		DEBUG(("readpipe_thread: post-ReadFile%d: %d read, err %d\n", iopipe_op->id, iopipe_op->nbytes,iopipe_op->error));
+		ReleaseSemaphore(iopipe_op->semaphore, 1, NULL);
+	}
+}
+
+proc *process_run(char executable[], char *args[], int timeout)
+{
+	proc *retval = NULL;
+	char *text;
+	int status;
+	tl_stream stdout_p;
+	tl_stream stdin_p;
+	SECURITY_ATTRIBUTES saAttr; 
+	PROCESS_INFORMATION pi;
+	STARTUPINFO si;
+	BOOL createproc_success = FALSE; 
+	BOOL timedout = FALSE; 
+	TCHAR *commandline = NULL;
+
+	proc *p = process_new();
+
+	if (p == NULL)
+		return NULL;
+
+	/* Make sure pipe handles are inherited */
+	saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
+	saAttr.bInheritHandle = TRUE; 
+	saAttr.lpSecurityDescriptor = NULL; 
+	
+	p->causeofdeath = PROC_PIPECREATE;
+
+	DEBUG(("making pipes \n"));
+	/* Child's Stdout */
+	if ( ! CreatePipe(&stdout_p.read, &stdout_p.write, &saAttr, 1) ) 
+	{
+		printlasterror();
+		RETURN(p);
+	}
+	DEBUG(("stdout done \n"));
+	
+	/* read handle to the pipe for STDOUT is not inherited */
+	if ( ! SetHandleInformation(stdout_p.read, HANDLE_FLAG_INHERIT, 0) )
+	{
+		printlasterror();
+		RETURN(p); 
+	}
+	DEBUG(("stdout noinherit \n"));
+	
+	/* a pipe for the child process's STDIN */
+	if ( ! CreatePipe(&stdin_p.read, &stdin_p.write, &saAttr, 0) ) 
+	{
+		printlasterror();
+		RETURN(p); 
+	}
+	DEBUG(("stdin done \n"));
+	
+	/*  write handle to the pipe for STDIN not inherited */
+	if ( ! SetHandleInformation(stdin_p.read, HANDLE_FLAG_INHERIT, 0) )
+	{
+		printlasterror();
+		RETURN(p); 
+	}
+	DEBUG(("pipes done \n"));
+	
+	
+	p->causeofdeath = PROC_START;
+
+	ZeroMemory( &si, sizeof(STARTUPINFO) );
+	ZeroMemory( &pi, sizeof(PROCESS_INFORMATION) );
+	
+	si.cb = sizeof(STARTUPINFO); 
+	si.hStdError = stdout_p.write;
+	si.hStdOutput = stdout_p.write;
+	/*
+	  Rather than use the stdin pipe, which would be
+       		  si.hStdInput = stdin_p.read;
+	  Pass on talon's own standard input to the child process
+	  This helps with programs like xcopy which demand that
+	  they are attached to a console and not just any type of
+	  input file.
+	 */
+	si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
+	si.dwFlags |= STARTF_USESTDHANDLES;
+
+	
+	DEBUG(("pre commandline \n"));
+	/* create the commandline string */
+	int len = 0;
+	int i = 0;
+	while (args[i] != NULL)
+	{
+		len += strlen(args[i++]) + 1;
+	}
+	len+=2;
+
+	commandline = malloc(len*2);
+	if (! commandline) 
+		RETURN(p);
+	commandline[0] = '\0';
+
+	i = 0;
+	while (args[i] != NULL)
+	{
+		strcat(commandline, args[i]);
+		strcat(commandline, " ");
+		i++;
+	}
+
+
+	/* Get the read thread ready to go before creating
+	 * the process.
+	 */
+	ReadOpQ *ropq  = malloc(sizeof(ReadOpQ));
+
+	ropq->first=NULL;
+	ropq->last=NULL;
+	ropq->semaphore = CreateSemaphore(NULL, 0, 1, NULL);
+	DEBUG(("Creating read thread. \n"));
+
+	DWORD readpipe_threadid;
+	HANDLE h_readpipe_thread = CreateThread(NULL, 8192, (LPTHREAD_START_ROUTINE) readpipe_thread, (void*)ropq, 0, &readpipe_threadid);
+
+	/* ready to run the process */
+ 
+	DEBUG(("process commandline:\n%s \n", commandline));
+	DEBUG(("\n"));
+	createproc_success = CreateProcess(executable, 
+	   commandline,     // command line 
+	   NULL,          // process security attributes 
+	   NULL,          // primary thread security attributes 
+	   TRUE,          // handles are inherited 
+	   0,             // creation flags 
+	   NULL,          // use parent's environment 
+	   NULL,          // use parent's current directory 
+	   &si,  // STARTUPINFO pointer 
+	   &pi);  // receives PROCESS_INFORMATION 
+
+	if (! createproc_success)
+	{
+		DEBUG(("Createprocess failed. \n"));
+		p->causeofdeath = PROC_SOMEODDDEATH;
+		RETURN(p);
+	}
+
+	int have_status = 0;
+
+
+	DEBUG(("Closing Handles. \n"));
+	if (!CloseHandle(stdout_p.write)) 
+		RETURN(p);
+	if (!CloseHandle(stdin_p.read)) 
+		RETURN(p);
+
+	DEBUG(("Closed Handles. \n"));
+
+
+	static int id=0;
+	do
+	{
+		char *space = buffer_makespace(p->output, READSIZE);
+
+		DWORD waitres;
+		ReadOp *iopipe_op = malloc(sizeof(ReadOp));
+		iopipe_op->semaphore = CreateSemaphore(NULL, 0, 1, NULL);
+		iopipe_op->thread =  h_readpipe_thread;
+		iopipe_op->timeout = timeout;
+		iopipe_op->file = stdout_p.read;
+		iopipe_op->space = malloc(READSIZE);
+		iopipe_op->id = id++;
+		iopipe_op->nbytes = READSIZE;
+		iopipe_op->next = NULL;
+
+		if (!ropq->first)
+		{
+			ropq->first = iopipe_op;
+			ropq->last = iopipe_op;
+		} else {
+			ropq->last->next = iopipe_op;
+			ropq->last = iopipe_op;
+		}
+
+		ReleaseSemaphore(ropq->semaphore, 1, NULL);
+
+		DEBUG(("waiting for read %d\n", timeout));
+		waitres = WaitForSingleObject(iopipe_op->semaphore, timeout);
+		DEBUG(("read wait finished result= %d\n", waitres));
+
+		if (waitres != WAIT_OBJECT_0)
+		{
+			DEBUG(("timeout \n"));
+			timedout = TRUE;
+			break;
+		}
+		else
+		{
+			DEBUG(("read signalled: nbytes: %d \n", iopipe_op->nbytes));
+			if (iopipe_op->nbytes <= 0)
+			{
+				break;
+			}
+			memcpy(space, iopipe_op->space, iopipe_op->nbytes);	
+			buffer_usespace(p->output, iopipe_op->nbytes);	
+			DEBUG(("buffer took on nbytes: %d \n", iopipe_op->nbytes));
+		}
+	}
+	while (1);
+
+	if (timedout == FALSE) 
+	{
+		DEBUG(("Wait for process exit\n"));
+		// Wait until child process exits.
+		WaitForSingleObject(pi.hProcess, INFINITE);
+		DEBUG(("Process exited\n"));
+
+		DWORD exitcode;
+
+		if (GetExitCodeProcess(pi.hProcess, &exitcode))
+		{
+			p->causeofdeath = PROC_NORMALDEATH;
+			p->returncode = exitcode;
+			DEBUG(("process exited normally = %d:\n", p->returncode));
+			RETURN(p);	
+		} else {
+			p->causeofdeath = PROC_SOMEODDDEATH;
+			p->returncode = 128;
+			DEBUG(("process terminated \n"));
+			RETURN(p);	
+		}
+	} else {
+		TerminateProcess(pi.hProcess,1);
+		p->causeofdeath = PROC_TIMEOUTDEATH;
+		p->returncode = 128;
+		DEBUG(("process timedout \n"));
+		RETURN(p);	
+	}
+
+	/* Clean up the read operation queue 
+	ReadOp *r = ropq.first;
+	do
+	{
+		CloseHandle(r->semaphore);
+		free(r->space);
+		free(r);
+		r = r->next;
+	} while (r != NULL); */
+
+	CLEANUP();
+	if (retval == NULL)
+	{
+		if (p)
+			process_free(&p);
+	}
+	if (commandline)
+		free(commandline);
+	
+	return retval;
+}
+
+void process_free(proc **pp)
+{
+	if (!pp)
+		return;
+	if (! *pp)
+		return;
+
+	if ((*pp)->output)
+		buffer_free(&((*pp)->output));
+	
+	free(*pp);
+
+	*pp = NULL;
+}
--- a/sbsv2/raptor/util/talon/sema.c	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/sema.c	Wed Jun 23 16:56:47 2010 +0800
@@ -1,137 +1,137 @@
-/*
-* 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: 
-*
-*/
-
-
-
-
-#include "sema.h"
-
-// OS specific headers
-#ifdef WIN32
-#include <windows.h>
-#include <tlhelp32.h>
-#else
-#include <semaphore.h>
-#include <sys/types.h>
-#include <signal.h>
-#include <fcntl.h>
-#include <time.h>
-#endif
-
-#include <unistd.h>
-
-
-void sema_create(sbs_semaphore *s)
-{
-#ifdef WIN32
-	s->handle = CreateSemaphore(NULL, 1, 1, s->name);
-	if (s->handle)
-		CloseHandle(s->handle);
-	else
-		error("unable to create semaphore %s", s->name);
-#else
-	s->handle = sem_open(s->name, O_CREAT | O_EXCL, 0644, 1);
-	
-  	if (s->handle == SEM_FAILED)
-	{
-		sem_close(s->handle);
-	  	error("unable to create semaphore %s", s->name);
-	}
-	sem_close(s->handle);
-#endif
-}
-
-void sema_destroy(sbs_semaphore *s)
-{
-	#ifdef WIN32
-		/* can't destroy a windows semaphore... */
-	#else
-  		if (sem_unlink(s->name) != 0)
-		  	error("unable to unlink semaphore", s->name);
-	#endif
-}
-
-
-int sema_wait(sbs_semaphore *s)
-{
-	/* try and open the semaphore now */
-        #ifdef WIN32
-		s->handle = CreateSemaphore(NULL, 1, 1, s->name);
-		if (!s->handle)
-		{
-			error("unable to open semaphore %s", s->name);
-			return -2;
-		}
-        #else
-		struct timespec tmout;
-		
-		s->handle = sem_open(s->name, 0);
-	
-	  	if (s->handle == SEM_FAILED)
-		{
-    			sem_close(s->handle);
-      			error("unable to open semaphore %s\n", s->name);
-			return -2;
-    		}
-	#endif
-    
-    /* wait for the semaphore to be free [timeout if it takes too long] */
- 	int timedOutFlag = 0;
-	int semcount = 0;
-	#ifdef WIN32
- 		timedOutFlag = (WaitForSingleObject(s->handle, s->timeout) != WAIT_OBJECT_0);
-	#else
-
-		sem_getvalue(s->handle, &semcount);
-      		debug("sema: count before wait: %d\n", semcount);
-      		debug("sema: timeout: %d\n", s->timeout);
-
-	        if (clock_gettime(CLOCK_REALTIME, &tmout) == -1)
-		{
-               		error("sema: clock_gettime failed - can't do timed wait");
-			return -1;
-		}
-
-		tmout.tv_sec += (s->timeout / 1000);
-		tmout.tv_nsec += (s->timeout % 1000) * 1000;
-		timedOutFlag = sem_timedwait(s->handle, &tmout); 
-		/* roughly speaking the return value indicates timeouts. It also indicated
-		 * signals.  We are glossing over this for the moment since it isn't really
-		 * interesting in this application 
-		 * */
-	#endif
-
-	return timedOutFlag;
-}
-
-
-void  sema_release(sbs_semaphore *s)
-{
-	/* release the semaphore */
-	#ifdef WIN32
-		ReleaseSemaphore(s->handle, 1, NULL);
-	#else
-	   	sem_post(s->handle);
-	#endif
-	
-	   /* clean up */
-	#ifdef WIN32
-		CloseHandle(s->handle);
-	#else
-	   	sem_close(s->handle);
-	#endif
-}
+/*
+* 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: 
+*
+*/
+
+
+
+
+#include "sema.h"
+
+// OS specific headers
+#ifdef WIN32
+#include <windows.h>
+#include <tlhelp32.h>
+#else
+#include <semaphore.h>
+#include <sys/types.h>
+#include <signal.h>
+#include <fcntl.h>
+#include <time.h>
+#endif
+
+#include <unistd.h>
+
+
+void sema_create(sbs_semaphore *s)
+{
+#ifdef WIN32
+	s->handle = CreateSemaphore(NULL, 1, 1, s->name);
+	if (s->handle)
+		CloseHandle(s->handle);
+	else
+		error("unable to create semaphore %s", s->name);
+#else
+	s->handle = sem_open(s->name, O_CREAT | O_EXCL, 0644, 1);
+	
+  	if (s->handle == SEM_FAILED)
+	{
+		sem_close(s->handle);
+	  	error("unable to create semaphore %s", s->name);
+	}
+	sem_close(s->handle);
+#endif
+}
+
+void sema_destroy(sbs_semaphore *s)
+{
+	#ifdef WIN32
+		/* can't destroy a windows semaphore... */
+	#else
+  		if (sem_unlink(s->name) != 0)
+		  	error("unable to unlink semaphore", s->name);
+	#endif
+}
+
+
+int sema_wait(sbs_semaphore *s)
+{
+	/* try and open the semaphore now */
+        #ifdef WIN32
+		s->handle = CreateSemaphore(NULL, 1, 1, s->name);
+		if (!s->handle)
+		{
+			error("unable to open semaphore %s", s->name);
+			return -2;
+		}
+        #else
+		struct timespec tmout;
+		
+		s->handle = sem_open(s->name, 0);
+	
+	  	if (s->handle == SEM_FAILED)
+		{
+    			sem_close(s->handle);
+      			error("unable to open semaphore %s\n", s->name);
+			return -2;
+    		}
+	#endif
+    
+    /* wait for the semaphore to be free [timeout if it takes too long] */
+ 	int timedOutFlag = 0;
+	int semcount = 0;
+	#ifdef WIN32
+ 		timedOutFlag = (WaitForSingleObject(s->handle, s->timeout) != WAIT_OBJECT_0);
+	#else
+
+		sem_getvalue(s->handle, &semcount);
+      		debug("sema: count before wait: %d\n", semcount);
+      		debug("sema: timeout: %d\n", s->timeout);
+
+	        if (clock_gettime(CLOCK_REALTIME, &tmout) == -1)
+		{
+               		error("sema: clock_gettime failed - can't do timed wait");
+			return -1;
+		}
+
+		tmout.tv_sec += (s->timeout / 1000);
+		tmout.tv_nsec += (s->timeout % 1000) * 1000;
+		timedOutFlag = sem_timedwait(s->handle, &tmout); 
+		/* roughly speaking the return value indicates timeouts. It also indicated
+		 * signals.  We are glossing over this for the moment since it isn't really
+		 * interesting in this application 
+		 * */
+	#endif
+
+	return timedOutFlag;
+}
+
+
+void  sema_release(sbs_semaphore *s)
+{
+	/* release the semaphore */
+	#ifdef WIN32
+		ReleaseSemaphore(s->handle, 1, NULL);
+	#else
+	   	sem_post(s->handle);
+	#endif
+	
+	   /* clean up */
+	#ifdef WIN32
+		CloseHandle(s->handle);
+	#else
+	   	sem_close(s->handle);
+	#endif
+}
--- a/sbsv2/raptor/util/talon/sema.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/sema.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,52 +1,52 @@
-/*
-* 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: 
-*
-*/
-
-
-
-
-#ifndef _SEMA_H_
-#define _SEMA_H_
-
-#ifdef WIN32
-#include <windows.h>
-#include <tlhelp32.h>
-#else
-#include <semaphore.h>
-#include <sys/types.h>
-#endif
-
-
-
-typedef struct
-{
-	char *name;
-	#ifdef WIN32
-	HANDLE handle;
-	#else
-	sem_t *handle;
-	#endif
-	unsigned int timeout;
-} sbs_semaphore;
-
-
-void sema_create(sbs_semaphore *s);
-void sema_destroy(sbs_semaphore *s);
-int sema_wait(sbs_semaphore *s);
-void  sema_release(sbs_semaphore *s);
-int sema_wait(sbs_semaphore *s);
-
-#endif
+/*
+* 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: 
+*
+*/
+
+
+
+
+#ifndef _SEMA_H_
+#define _SEMA_H_
+
+#ifdef WIN32
+#include <windows.h>
+#include <tlhelp32.h>
+#else
+#include <semaphore.h>
+#include <sys/types.h>
+#endif
+
+
+
+typedef struct
+{
+	char *name;
+	#ifdef WIN32
+	HANDLE handle;
+	#else
+	sem_t *handle;
+	#endif
+	unsigned int timeout;
+} sbs_semaphore;
+
+
+void sema_create(sbs_semaphore *s);
+void sema_destroy(sbs_semaphore *s);
+int sema_wait(sbs_semaphore *s);
+void  sema_release(sbs_semaphore *s);
+int sema_wait(sbs_semaphore *s);
+
+#endif
--- a/sbsv2/raptor/util/talon/talon.c	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/talon.c	Wed Jun 23 16:56:47 2010 +0800
@@ -1,613 +1,646 @@
-/*
-* 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: 
-*
-*/
-
-
-
-
-#include <stdlib.h>
-#include <unistd.h>
-#include <string.h>
-#include <stdio.h>
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <stdarg.h>
-
-#include "talon_process.h"
-#include "sema.h"
-#include "buffer.h"
-#include "../config.h"
-
-/* The output semaphore. */
-sbs_semaphore talon_sem;
-
-#define TALON_ATTEMPT_STRMAX 32
-#define RECIPETAG_STRMAX 2048
-#define STATUS_STRMAX 100
-
-#define TALONDELIMITER '|'
-#define VARNAMEMAX 100
-#define VARVALMAX 1024
-
-
-#include "log.h"
-
-#ifdef HAS_MSVCRT
-/* Make all output handling binary */
-unsigned int _CRT_fmode = _O_BINARY;
-#endif
-
-double getseconds(void)
-{
-	struct timeval tp;
-	gettimeofday(&tp, NULL);
-
-	return (double)tp.tv_sec + ((double)tp.tv_usec)/1000000.0L;
-}
-
-void talon_setenv(char name[], char val[])
-{
-#if defined(HAS_GETENVIRONMENTVARIABLE)
-	SetEnvironmentVariableA(name,val); 
-#elif defined(HAS_GETENV)
-	setenv(name,val, 1);
-#else
-#	error "Need a function for setting environment variables"
-#endif
-}
-
-
-#define TALON_MAXENV 4096
-char * talon_getenv(char name[])
-{
-#if defined(HAS_SETENV)
-	char *val = getenv(name);
-	char *dest = NULL;
-	
-	if (val)
-	{
-		dest = malloc(strlen(val) + 1);
-		if (dest)
-		{
-			strcpy(dest,val);
-		}
-	}
-	return dest;
-#elif defined(HAS_SETENVIRONMENTVARIABLE)
-	char *val = malloc(TALON_MAXENV);
-	if (0 != GetEnvironmentVariableA(name,val,TALON_MAXENV-1))
-		return val;
-	else
-		return NULL;
-#else
-#	error "Need a function for setting environment variables"
-#endif
-}
-
-void prependattributes(buffer *b, char *attributes)
-{
-	char recipetag[RECIPETAG_STRMAX];
-	char *rt;
-	char envvarname[VARNAMEMAX];
-	char *att;
-	
-	
-        strcpy(recipetag, "<recipe ");
-	rt = recipetag + 8;
-
-	att = attributes;
-	while (*att != '\0' && rt < &recipetag[RECIPETAG_STRMAX-1])
-	{
-		if ( *att == '$' )
-		{
-			int e;
-			char *v;
-			/* insert the value of an environent variable */
-			att++;
-			e = 0;	
-			do {
-				envvarname[e++] = *att;
-				att++;
-			} while ( e < (VARNAMEMAX-1) && (isalnum(*att) || *att == '_'));
-			envvarname[e] = '\0';
-/* DEBUG(("envvarname: %s\n", envvarname)); */
-			v = talon_getenv(envvarname);
-			if (v)
-			{
-				/* DEBUG(("     value: %s\n", v)); */
-				char *oldv=v;
-				while (*v != '\0' && rt < &recipetag[RECIPETAG_STRMAX-1])
-				{
-					*rt = *v;
-					rt++; v++;
-				}
-				free(oldv);
-			}
-		} else {
-			*rt = *att;
-			rt++; att++;
-		}
-	}
-
-	char *finish = ">\n<![CDATA[\n";
-	
-	while (*finish != '\0' && rt < &recipetag[RECIPETAG_STRMAX-1])
-	{
-		*rt = *finish;
-		*rt++; finish++;
-	}
-
-	*rt = '\0';
-
-        buffer_prepend(b, recipetag, strlen(recipetag));
-}
-
-/* read a recipe string from a temporary file.
- *
- * We only expect to do this for very long command lines on
- * Windows. So allocate the maximum size for CreateProcess on
- * Win32 (32768 bytes) and error if the file is longer than that. 
- *
- */
-char *read_recipe_from_file(const char *filename)
-{
-	FILE *fp = fopen(filename, "r");
-
-	if (!fp)
-	{
-		error("talon: error: could not read '%s'\n", filename);
-		return NULL;
-	}
-
-	int max_length = 32768;
-	char *recipe = (char*)malloc(max_length);
-
-	if (!recipe)
-	{
-		error("talon: error: could not allocate memory to read '%s'\n", filename);
-		return NULL;
-	}
-	int position = 0;
-
-	/* read the file one character at a time */
-	int c;
-	while ((c = getc(fp)) != EOF)
-	{
-		switch (c)
-		{
-			case '\r':
-			case '\n':
-				/* ignore newlines */
-				break;
-
-			case '"':
-				/* double quotes have to be escaped so they aren't lost later */
-				if (position < max_length)
-					recipe[position++] = '\\';
-				if (position < max_length)
-					recipe[position++] = c;
-				break;
-
-			default:
-				if (position < max_length)
-					recipe[position++] = c;
-				break;
-		}
-	}
-	fclose(fp);
-
-	/* add a terminating \0 */
-	if (position < max_length)
-		recipe[position] = '\0';
-	else
-	{
-		error("talon: error: command longer than 32768 in '%s'\n", filename);
-		return NULL;
-	}
-	return recipe;
-}
-
-int main(int argc, char *argv[])
-{
-	/* find the argument to -c then strip the talon related front section */
-
-	char *recipe = NULL;
-	int talon_returncode = 0;
-
-#ifdef HAS_GETCOMMANDLINE
-	char *commandline= GetCommandLine();
-	DEBUG(("talon: commandline: %s\n", commandline));
-	/*
-	 * The command line should be either,
-	 * talon -c "some shell commands"
-	 * or
-	 * talon shell_script_file
-	 *
-	 * talon could be an absolute path and may have a .exe extension.
-	 */
-	recipe = strstr(commandline, "-c");
-	if (recipe)
-	{
-		/* there was a -c so extract the quoted commands */
-
-		while (*recipe != '"' && *recipe != '\0')
-			recipe++;
-
-		if (*recipe != '"')    /* we found -c but no following quote */
-		{
-			error("talon: error: unquoted recipe in shell call '%s'\n", commandline);
-			return 1;
-		}
-		recipe++;
-		
-		int recipelen = strlen(recipe);
-		if (recipelen > 0 && recipe[recipelen - 1] == '"')
-			recipe[recipelen - 1] = '\0'; /* remove trailing quote */
-	}
-	else
-	{
-		/* there was no -c so extract the argument as a filename */
-
-		recipe = strstr(commandline, "talon");
-		if (recipe)
-		{
-			/* find the first space */
-			while (!isspace(*recipe) && *recipe != '\0')
-				recipe++;
-			/* skip past the spaces */
-			while (isspace(*recipe))
-				recipe++;
-
-			recipe = read_recipe_from_file(recipe);
-
-			if (!recipe)
-			{
-			    error("talon: error: bad script file in shell call '%s'\n", commandline);
-				return 1;
-			}
-		}
-		else
-		{
-			error("talon: error: no 'talon' in shell call '%s'\n", commandline);
-			return 1;
-		}
-	}
-#else
-	/*
-	 * The command line should be either,
-	 * talon -c "some shell commands"
-	 * or
-	 * talon shell_script_file
-	 *
-	 * talon could be an absolute path and may have a .exe extension.
-	 */
-	switch (argc)
-	{
-		case 2:
-			recipe = read_recipe_from_file(argv[1]);
-			break;
-		case 3:
-			if (strcmp("-c", argv[1]) != 0)
-			{
-				error("talon: error: %s\n", "usage is 'talon -c command' or 'talon script_filename'");
-				return 1;
-			}
-			recipe = argv[2];
-			break;
-		default:
-			error("talon: error: %s\n", "usage is 'talon -c command' or 'talon script_filename'");
-			return 1;
-	}
-#endif
-
-	/* did we get a recipe at all? */
-	if (!recipe)
-	{
-		error("talon: error: %s", "no recipe supplied to the shell.\n");
-		return 1;
-	}
-
-	/* remove any leading white space on the recipe */
-	while (isspace(*recipe))
-		recipe++;
-
-	/* turn debugging on? */
-	char *debugstr=talon_getenv("TALON_DEBUG");
-
-	if (debugstr)
-	{
-		loglevel=LOGDEBUG;
-		free(debugstr); debugstr=NULL;
-	}
-
-	DEBUG(("talon: recipe: %s\n", recipe));
-
-	
-	char varname[VARNAMEMAX];
-	char varval[VARVALMAX];
-	int dotagging = 0; 
-	int force_descramble_off = 0;
-
-	char  *rp = recipe;
-	if (*rp == TALONDELIMITER) {
-		dotagging = 1; 
-
-		/* there are some talon-specific settings 
-		 * in the command which must be stripped */
-		rp++;
-		char *out = varname;
-		char *stopout = varname + VARNAMEMAX - 1;
-		DEBUG(("talon: parameters found\n"));
-		while (*rp != '\0')
-		{
-			
-			switch (*rp) {
-				case  '=':
-					*out = '\0';
-					DEBUG(("talon: varname: %s\n",varname));
-					out = varval;
-					stopout = varval + VARVALMAX - 1;
-					break;
-				case ';':
-					*out = '\0';
-					DEBUG(("talon: varval: %s\n",varval));
-					talon_setenv(varname, varval);
-					out = varname;
-					stopout = varname + VARNAMEMAX - 1;
-					break;
-				default:	
-					*out = *rp;
-					if (out < stopout)
-						out++;
-					break;
-			}
-
-			if (*rp == TALONDELIMITER)
-			{
-				rp++;
-				break;
-			}
-			
-			rp++;
-		}
-	} else {
-		/* This is probably a $(shell) statement 
- 		 * in make so no descrambling needed and 
- 		 * tags are definitely not wanted as they 
- 		 * would corrupt the expected output*/
-		force_descramble_off = 1; 
-	}
-
-
-	/* Now take settings from the environment (having potentially modified it) */	
-	if (talon_getenv("TALON_DEBUG"))
-		loglevel=LOGDEBUG;
-	
-
-	int enverrors = 0;
-
-	char *shell = talon_getenv("TALON_SHELL");
-	if (!shell)
-	{
-		error("error: %s", "TALON_SHELL not set in environment\n");
-		enverrors++;	
-	}
-
-	int timeout = -1;
-	char *timeout_str = talon_getenv("TALON_TIMEOUT");
-	if (timeout_str)
-	{
-		timeout = atoi(timeout_str);
-		free(timeout_str); timeout_str = NULL;
-	}
-
-	char *buildid = talon_getenv("TALON_BUILDID");
-	if (!buildid)
-	{
-		error("error: %s", "TALON_BUILDID not set in environment\n");
-		enverrors++;	
-	}
-
-	char *attributes = talon_getenv("TALON_RECIPEATTRIBUTES");
-	if (!attributes)
-	{
-		error("error: %s", "TALON_RECIPEATTRIBUTES not set in environment\n");
-		enverrors++;
-	}
-
-
-	int max_retries = 0;
-	char *retries_str = talon_getenv("TALON_RETRIES");
-	if (retries_str)
-	{
-		max_retries = atoi(retries_str);
-		free(retries_str); retries_str = NULL;
-	}	
-
-
-	int descramble = 0;
-	if (! force_descramble_off )
-	{
-		char *descramblestr = talon_getenv("TALON_DESCRAMBLE");
-		if (descramblestr)
-		{
-			if (*descramblestr == '0')
-				descramble = 0;
-			else
-				descramble = 1;
-		
-			free(descramblestr); descramblestr = NULL;
-		}
-	}
-
-
-
-	/* Talon can look in a flags variable to alter it's behaviour */
-	int force_success = 0;
-	char *flags_str = talon_getenv("TALON_FLAGS");
-	if (flags_str)
-	{
-		int c;
-		for (c=0; flags_str[c] !=0; c++)
-			flags_str[c] = tolower(flags_str[c]);
-
-		if (strstr(flags_str, "forcesuccess"))
-			force_success = 1;
-
-		/* don't put <recipe> or <CDATA<[[ tags around the output. e.g. if it's XML already*/
-		if (strstr(flags_str, "rawoutput"))
-		{
-			dotagging = 0;
-		}
-
-		free(flags_str); flags_str = NULL;
-	}	
-
-	/* Talon subprocesses need to have the "correct" shell variable set. */
-	talon_setenv("SHELL", shell); 
-
-	/* we have allowed some errors to build up so that the user
-	 * can see all of them before we stop and force the user 
-	 * to fix them
-	 */
-	if (enverrors)
-	{
-		return 1;
-	}
-
-	
-	/* Run the recipe repeatedly until the retry count expires or
-	 * it succeeds.
-	 */
-	int attempt = 0, retries = max_retries;
-	proc *p = NULL;
-
-	char *args[5];
-
-	char *qrp=rp;
-
-#ifdef HAS_GETCOMMANDLINE
-	/* re-quote the argument to -c since this helps windows deal with it */
-	int qrpsize = strlen(rp) + 3;
-	qrp = malloc(qrpsize);
-	qrp[0] = '"';
-	strcpy(&qrp[1], rp);
-	qrp[qrpsize-2] = '"';
-	qrp[qrpsize-1] = '\0';
-#endif
-
-	int index = 0;
-	args[index++] = shell;
-
-	if (dotagging)  /* don't do bash -x for non-tagged commands e.g. $(shell output) */
-		args[index++] = "-x";
-
-	args[index++] = "-c";
-	args[index++] = qrp;
-	args[index++] = NULL;
-
-	/* get the semaphore ready */
-	talon_sem.name = buildid;
-	talon_sem.timeout = timeout;
-	do
-	{
-		char talon_attempt[TALON_ATTEMPT_STRMAX];
-		double start_time = getseconds();
-		
-		attempt++;
-		
-		snprintf(talon_attempt, TALON_ATTEMPT_STRMAX-1, "%d", attempt);
-		talon_attempt[TALON_ATTEMPT_STRMAX - 1] = '\0';
-
-		talon_setenv("TALON_ATTEMPT", talon_attempt);
-		
-		p = process_run(shell, args, timeout);
-
-		double end_time = getseconds();
-		
-		if (p) 
-		{
-			char status[STATUS_STRMAX];
-			char timestat[STATUS_STRMAX];
-
-			talon_returncode = p->returncode;
-
-			if (dotagging) 
-			{
-				char *forcesuccessstr = force_success == 0 ? "" : " forcesuccess='FORCESUCCESS'";
-
-				if (p->returncode != 0)
-				{
-					char *exitstr = retries > 0 ? "retry" : "failed";
-					snprintf(status, STATUS_STRMAX - 1, "\n<status exit='%s' code='%d' attempt='%d'%s />", exitstr, p->returncode, attempt, forcesuccessstr );
-				} else {
-					snprintf(status, STATUS_STRMAX - 1, "\n<status exit='ok' attempt='%d'%s />", attempt, forcesuccessstr );
-				}
-				status[STATUS_STRMAX-1] = '\0';
-	
-				snprintf(timestat, STATUS_STRMAX - 1, "<time start='%.5f' elapsed='%.3f' />",start_time, end_time-start_time );
-				timestat[STATUS_STRMAX-1] = '\0';
-
-				prependattributes(p->output, attributes);
-			
-			if (dotagging) {
-			}
-				buffer_append(p->output, "\n]]>", 4);
-				buffer_append(p->output, timestat, strlen(timestat));
-				buffer_append(p->output, status, strlen(status));
-				buffer_append(p->output, "\n</recipe>\n", 11);
-			}
-		
-			unsigned int iterator = 0;
-			byteblock *bb;
-		
-			if (descramble)	
-				sema_wait(&talon_sem);
-			while ((bb = buffer_getbytes(p->output, &iterator)))
-			{
-				write(STDOUT_FILENO, &bb->byte0, bb->fill);
-			}
-			if (descramble)	
-				sema_release(&talon_sem);
-		
-		
-			if (p->returncode == 0 || force_success)
-			{
-				process_free(&p);
-				break;
-			}
-
-			process_free(&p);
-		} else {
-			error("error: failed to run shell: %s: check the SHELL environment variable.\n", args[0]);
-			return 1;
-		}
-
-		retries--;
-	}
-	while (retries >= 0);
-
-	if (buildid) free(buildid); buildid = NULL;
-	if (attributes) free(attributes); attributes = NULL;
-	if (shell) free(shell); shell = NULL;
-
-	if (force_success)
-		return 0;
-	else 
-		return talon_returncode;
-}
+/*
+* Copyright (c) 2009-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: 
+*
+*/
+
+
+#ifdef HAS_WINSOCK2
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#define WIN32_LEAN_AND_MEAN
+#endif
+
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include <stdio.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <stdarg.h>
+
+#include "talon_process.h"
+#include "sema.h"
+#include "buffer.h"
+#include "../config.h"
+
+#ifdef HAS_GETCOMMANDLINE
+#include "chomp.h"
+#endif
+
+/* The output semaphore. */
+sbs_semaphore talon_sem;
+
+#define TALON_ATTEMPT_STRMAX 32
+#define RECIPETAG_STRMAX 2048
+#define STATUS_STRMAX 120
+
+#define TALONDELIMITER '|'
+#define VARNAMEMAX 100
+#define VARVALMAX 1024
+
+#define HOSTNAME_MAX 100
+
+
+#include "log.h"
+
+#ifdef HAS_MSVCRT
+/* Make all output handling binary */
+unsigned int _CRT_fmode = _O_BINARY;
+#endif
+
+
+double getseconds(void)
+{
+	struct timeval tp;
+	gettimeofday(&tp, NULL);
+
+	return (double)tp.tv_sec + ((double)tp.tv_usec)/1000000.0L;
+}
+
+void talon_setenv(char name[], char val[])
+{
+#if defined(HAS_GETENVIRONMENTVARIABLE)
+	SetEnvironmentVariableA(name,val); 
+#elif defined(HAS_GETENV)
+	setenv(name,val, 1);
+#else
+#	error "Need a function for setting environment variables"
+#endif
+}
+
+
+#define TALON_MAXENV 4096
+char * talon_getenv(char name[])
+{
+#if defined(HAS_SETENV)
+	char *val = getenv(name);
+	char *dest = NULL;
+	
+	if (val)
+	{
+		dest = malloc(strlen(val) + 1);
+		if (dest)
+		{
+			strcpy(dest,val);
+		}
+	}
+	return dest;
+#elif defined(HAS_SETENVIRONMENTVARIABLE)
+	char *val = malloc(TALON_MAXENV);
+	if (0 != GetEnvironmentVariableA(name,val,TALON_MAXENV-1))
+		return val;
+	else
+		return NULL;
+#else
+#	error "Need a function for setting environment variables"
+#endif
+}
+
+void prependattributes(buffer *b, char *attributes)
+{
+	char recipetag[RECIPETAG_STRMAX];
+	char *rt;
+	char envvarname[VARNAMEMAX];
+	char *att;
+	
+	
+        strcpy(recipetag, "<recipe ");
+	rt = recipetag + 8;
+
+	att = attributes;
+	while (*att != '\0' && rt < &recipetag[RECIPETAG_STRMAX-1])
+	{
+		if ( *att == '$' )
+		{
+			int e;
+			char *v;
+			/* insert the value of an environent variable */
+			att++;
+			e = 0;	
+			do {
+				envvarname[e++] = *att;
+				att++;
+			} while ( e < (VARNAMEMAX-1) && (isalnum(*att) || *att == '_'));
+			envvarname[e] = '\0';
+			/* DEBUG(("envvarname: %s\n", envvarname));*/ 
+			v = talon_getenv(envvarname);
+			if (v)
+			{
+				/* DEBUG(("     value: %s\n", v)); */
+				char *oldv=v;
+				while (*v != '\0' && rt < &recipetag[RECIPETAG_STRMAX-1])
+				{
+					*rt = *v;
+					rt++; v++;
+				}
+				free(oldv);
+			}
+		} else {
+			*rt = *att;
+			rt++; att++;
+		}
+	}
+
+	char *finish = ">\n<![CDATA[\n";
+	
+	while (*finish != '\0' && rt < &recipetag[RECIPETAG_STRMAX-1])
+	{
+		*rt = *finish;
+		*rt++; finish++;
+	}
+
+	*rt = '\0';
+
+        buffer_prepend(b, recipetag, strlen(recipetag));
+}
+
+/* read a recipe string from a temporary file.
+ *
+ * We only expect to do this for very long command lines on
+ * Windows. So allocate the maximum size for CreateProcess on
+ * Win32 (32768 bytes) and error if the file is longer than that. 
+ *
+ */
+char *read_recipe_from_file(const char *filename)
+{
+	FILE *fp = fopen(filename, "r");
+
+	if (!fp)
+	{
+		error("talon: error: could not read '%s'\n", filename);
+		return NULL;
+	}
+
+	int max_length = 32768;
+	char *recipe = (char*)malloc(max_length);
+
+	if (!recipe)
+	{
+		error("talon: error: could not allocate memory to read '%s'\n", filename);
+		return NULL;
+	}
+	int position = 0;
+
+	/* read the file one character at a time */
+	int c;
+	while ((c = getc(fp)) != EOF)
+	{
+		switch (c)
+		{
+			case '\r':
+			case '\n':
+				/* ignore newlines */
+				break;
+
+			case '"':
+				/* double quotes have to be escaped so they aren't lost later */
+				if (position < max_length)
+					recipe[position++] = '\\';
+				if (position < max_length)
+					recipe[position++] = c;
+				break;
+
+			default:
+				if (position < max_length)
+					recipe[position++] = c;
+				break;
+		}
+	}
+	fclose(fp);
+
+	/* add a terminating \0 */
+	if (position < max_length)
+		recipe[position] = '\0';
+	else
+	{
+		error("talon: error: command longer than 32768 in '%s'\n", filename);
+		return NULL;
+	}
+	return recipe;
+}
+
+int main(int argc, char *argv[])
+{
+	/* find the argument to -c then strip the talon related front section */
+
+	char *recipe = NULL;
+	int talon_returncode = 0;
+
+#ifdef HAS_WINSOCK2
+	WSADATA wsaData;
+
+	WSAStartup(MAKEWORD(2,2), &wsaData);
+
+	/* We ignore the result as we are only doing this to use gethostname
+	   and if that fails then leaving the host attribute blank is perfectly
+	   acceptable.
+	*/
+
+#endif
+
+#ifdef HAS_GETCOMMANDLINE
+	char *commandline= GetCommandLine();
+	/*
+	 * The command line should be either,
+	 * talon -c "some shell commands"
+	 * or
+	 * talon shell_script_file
+	 *
+	 * talon could be an absolute path and may have a .exe extension.
+	 */
+
+	
+	recipe = chompCommand(commandline);
+	if (recipe)
+	{
+		/* there was a -c so extract the quoted commands */
+
+		int recipelen = strlen(recipe);
+		if (recipelen > 0 && recipe[recipelen - 1] == '"')
+			recipe[recipelen - 1] = '\0'; /* remove trailing quote */
+	}
+	else
+	{
+		/* there was no -c so extract the argument as a filename */
+
+		recipe = strstr(commandline, "talon");
+		if (recipe)
+		{
+			/* find the first space */
+			while (!isspace(*recipe) && *recipe != '\0')
+				recipe++;
+			/* skip past the spaces */
+			while (isspace(*recipe))
+				recipe++;
+
+			recipe = read_recipe_from_file(recipe);
+
+			if (!recipe)
+			{
+			    error("talon: error: bad script file in shell call '%s'\n", commandline);
+				return 1;
+			}
+		}
+		else
+		{
+			error("talon: error: no 'talon' in shell call '%s'\n", commandline);
+			return 1;
+		}
+	}
+#else
+	/*
+	 * The command line should be either,
+	 * talon -c "some shell commands"
+	 * or
+	 * talon shell_script_file
+	 *
+	 * talon could be an absolute path and may have a .exe extension.
+	 */
+	switch (argc)
+	{
+		case 2:
+			recipe = read_recipe_from_file(argv[1]);
+			break;
+		case 3:
+			if (strcmp("-c", argv[1]) != 0)
+			{
+				error("talon: error: %s\n", "usage is 'talon -c command' or 'talon script_filename'");
+				return 1;
+			}
+			recipe = argv[2];
+			break;
+		default:
+			error("talon: error: %s\n", "usage is 'talon -c command' or 'talon script_filename'");
+			return 1;
+	}
+#endif
+
+	/* did we get a recipe at all? */
+	if (!recipe)
+	{
+		error("talon: error: %s", "no recipe supplied to the shell.\n");
+		return 1;
+	}
+
+	/* remove any leading white space on the recipe */
+	while (isspace(*recipe))
+		recipe++;
+
+	/* turn debugging on? */
+	char *debugstr=talon_getenv("TALON_DEBUG");
+
+	if (debugstr)
+	{
+		loglevel=LOGDEBUG;
+		free(debugstr); debugstr=NULL;
+	}
+
+	DEBUG(("talon: recipe: %s\n", recipe));
+
+	/* Make sure that the agent's hostname can be put into the host attribute */
+	char hostname[HOSTNAME_MAX];
+	int hostresult=0;
+	
+	hostresult = gethostname(hostname, HOSTNAME_MAX-1);
+	if (0 != hostresult)
+	{
+		DEBUG(("talon: failed to get hostname: %d\n", hostresult));
+		hostname[0] = '\0';
+	}
+
+	talon_setenv("HOSTNAME", hostname);
+	DEBUG(("talon: setenv: hostname: %s\n", hostname));
+
+	
+	char varname[VARNAMEMAX];
+	char varval[VARVALMAX];
+	int dotagging = 0; 
+	int force_descramble_off = 0;
+
+	char  *rp = recipe;
+	if (*rp == TALONDELIMITER) {
+		dotagging = 1; 
+
+		/* there are some talon-specific settings 
+		 * in the command which must be stripped */
+		rp++;
+		char *out = varname;
+		char *stopout = varname + VARNAMEMAX - 1;
+		DEBUG(("talon: parameters found\n"));
+		while (*rp != '\0')
+		{
+			
+			switch (*rp) {
+				case  '=':
+					*out = '\0';
+					DEBUG(("talon: varname: %s\n",varname));
+					out = varval;
+					stopout = varval + VARVALMAX - 1;
+					break;
+				case ';':
+					*out = '\0';
+					DEBUG(("talon: varval: %s\n",varval));
+					talon_setenv(varname, varval);
+					out = varname;
+					stopout = varname + VARNAMEMAX - 1;
+					break;
+				default:	
+					*out = *rp;
+					if (out < stopout)
+						out++;
+					break;
+			}
+
+			if (*rp == TALONDELIMITER)
+			{
+				rp++;
+				break;
+			}
+			
+			rp++;
+		}
+	} else {
+		/* This is probably a $(shell) statement 
+ 		 * in make so no descrambling needed and 
+ 		 * tags are definitely not wanted as they 
+ 		 * would corrupt the expected output*/
+		force_descramble_off = 1; 
+	}
+
+
+	/* Now take settings from the environment (having potentially modified it) */	
+	if (talon_getenv("TALON_DEBUG"))
+		loglevel=LOGDEBUG;
+	
+
+	int enverrors = 0;
+
+	char *shell = talon_getenv("TALON_SHELL");
+	if (!shell)
+	{
+		error("error: %s", "TALON_SHELL not set in environment\n");
+		enverrors++;	
+	}
+
+	int timeout = -1;
+	char *timeout_str = talon_getenv("TALON_TIMEOUT");
+	if (timeout_str)
+	{
+		timeout = atoi(timeout_str);
+		free(timeout_str); timeout_str = NULL;
+	}
+
+	char *buildid = talon_getenv("TALON_BUILDID");
+	if (!buildid)
+	{
+		error("error: %s", "TALON_BUILDID not set in environment\n");
+		enverrors++;	
+	}
+
+	char *attributes = talon_getenv("TALON_RECIPEATTRIBUTES");
+	if (!attributes)
+	{
+		error("error: %s", "TALON_RECIPEATTRIBUTES not set in environment\n");
+		enverrors++;
+	}
+
+
+	int max_retries = 0;
+	char *retries_str = talon_getenv("TALON_RETRIES");
+	if (retries_str)
+	{
+		max_retries = atoi(retries_str);
+		free(retries_str); retries_str = NULL;
+	}	
+
+
+	int descramble = 0;
+	if (! force_descramble_off )
+	{
+		char *descramblestr = talon_getenv("TALON_DESCRAMBLE");
+		if (descramblestr)
+		{
+			if (*descramblestr == '0')
+				descramble = 0;
+			else
+				descramble = 1;
+		
+			free(descramblestr); descramblestr = NULL;
+		}
+	}
+
+
+
+	/* Talon can look in a flags variable to alter it's behaviour */
+	int force_success = 0;
+	char *flags_str = talon_getenv("TALON_FLAGS");
+	if (flags_str)
+	{
+		int c;
+		for (c=0; flags_str[c] !=0; c++)
+			flags_str[c] = tolower(flags_str[c]);
+
+		if (strstr(flags_str, "forcesuccess"))
+			force_success = 1;
+
+		/* don't put <recipe> or <CDATA<[[ tags around the output. e.g. if it's XML already*/
+		if (strstr(flags_str, "rawoutput"))
+		{
+			dotagging = 0;
+		}
+
+		free(flags_str); flags_str = NULL;
+	}	
+
+	/* Talon subprocesses need to have the "correct" shell variable set. */
+	talon_setenv("SHELL", shell); 
+
+	/* we have allowed some errors to build up so that the user
+	 * can see all of them before we stop and force the user 
+	 * to fix them
+	 */
+	if (enverrors)
+	{
+		return 1;
+	}
+
+	
+	/* Run the recipe repeatedly until the retry count expires or
+	 * it succeeds.
+	 */
+	int attempt = 0, retries = max_retries;
+	proc *p = NULL;
+
+	char *args[5];
+
+	char *qrp=rp;
+
+#ifdef HAS_GETCOMMANDLINE
+	/* re-quote the argument to -c since this helps windows deal with it */
+	int qrpsize = strlen(rp) + 3;
+	qrp = malloc(qrpsize);
+	qrp[0] = '"';
+	strcpy(&qrp[1], rp);
+	qrp[qrpsize-2] = '"';
+	qrp[qrpsize-1] = '\0';
+#endif
+
+	int index = 0;
+	args[index++] = shell;
+
+	if (dotagging)  /* don't do bash -x for non-tagged commands e.g. $(shell output) */
+		args[index++] = "-x";
+
+	args[index++] = "-c";
+	args[index++] = qrp;
+	args[index++] = NULL;
+
+	/* get the semaphore ready */
+	talon_sem.name = buildid;
+	talon_sem.timeout = timeout;
+	do
+	{
+		char talon_attempt[TALON_ATTEMPT_STRMAX];
+		double start_time = getseconds();
+		
+		attempt++;
+		
+		snprintf(talon_attempt, TALON_ATTEMPT_STRMAX-1, "%d", attempt);
+		talon_attempt[TALON_ATTEMPT_STRMAX - 1] = '\0';
+
+		talon_setenv("TALON_ATTEMPT", talon_attempt);
+		
+		p = process_run(shell, args, timeout);
+
+		double end_time = getseconds();
+		
+		if (p) 
+		{
+			char status[STATUS_STRMAX];
+			char timestat[STATUS_STRMAX];
+
+			talon_returncode = p->returncode;
+
+			if (dotagging) 
+			{
+				char *flagsstr = force_success == 0 ? "" : " flags='FORCESUCCESS'";
+				char *reasonstr = "" ;
+
+				if (p->causeofdeath == PROC_TIMEOUTDEATH)
+					reasonstr = " reason='timeout'";
+
+				if (p->returncode != 0)
+				{
+					char *exitstr = (force_success || retries <= 0) ? "failed" : "retry";
+					snprintf(status, STATUS_STRMAX - 1, "\n<status exit='%s' code='%d' attempt='%d'%s%s />", exitstr, p->returncode, attempt, flagsstr, reasonstr );
+				} else {
+					snprintf(status, STATUS_STRMAX - 1, "\n<status exit='ok' attempt='%d'%s%s />", attempt, flagsstr, reasonstr );
+				}
+				status[STATUS_STRMAX-1] = '\0';
+	
+				snprintf(timestat, STATUS_STRMAX - 1, "<time start='%.5f' elapsed='%.3f' />",start_time, end_time-start_time );
+				timestat[STATUS_STRMAX-1] = '\0';
+
+				prependattributes(p->output, attributes);
+			
+			if (dotagging) {
+			}
+				buffer_append(p->output, "\n]]>", 4);
+				buffer_append(p->output, timestat, strlen(timestat));
+				buffer_append(p->output, status, strlen(status));
+				buffer_append(p->output, "\n</recipe>\n", 11);
+			}
+		
+			unsigned int iterator = 0;
+			byteblock *bb;
+		
+			if (descramble)	
+				sema_wait(&talon_sem);
+			while ((bb = buffer_getbytes(p->output, &iterator)))
+			{
+				write(STDOUT_FILENO, &bb->byte0, bb->fill);
+			}
+			if (descramble)	
+				sema_release(&talon_sem);
+		
+		
+			if (p->returncode == 0 || force_success)
+			{
+				process_free(&p);
+				break;
+			}
+
+			process_free(&p);
+		} else {
+			error("error: failed to run shell: %s: check the SHELL environment variable.\n", args[0]);
+			return 1;
+		}
+
+		retries--;
+	}
+	while (retries >= 0);
+
+	if (buildid) free(buildid); buildid = NULL;
+	if (attributes) free(attributes); attributes = NULL;
+	if (shell) free(shell); shell = NULL;
+
+	if (force_success)
+		return 0;
+	else 
+		return talon_returncode;
+}
--- a/sbsv2/raptor/util/talon/talon_process.h	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/talon_process.h	Wed Jun 23 16:56:47 2010 +0800
@@ -1,54 +1,54 @@
-/*
-* 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: 
-*
-*/
-
-
-
-
-/*
- * Process.h
- */
-
-
-#ifndef _TALON_PROCESS_H_
-#define _TALON_PROCESS_H_
-
-#include <sys/types.h>
-#include "buffer.h"
-
-typedef pid_t proc_handle;
-
-#define PROC_NORMALDEATH 0
-#define PROC_TIMEOUTDEATH 1
-#define PROC_SOMEODDDEATH 2
-#define PROC_PIPECREATE 3
-#define PROC_START 4
-
-
-typedef struct 
-{
-	proc_handle pid;
-	unsigned int starttime;
-	unsigned int endtime;
-	int returncode;
-	unsigned int causeofdeath;
-	buffer *output;
-} proc;
-
-proc *process_run(char executable[], char *args[], int timeout);
-void process_free(proc **pp);
-	
-#endif
+/*
+* 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: 
+*
+*/
+
+
+
+
+/*
+ * Process.h
+ */
+
+
+#ifndef _TALON_PROCESS_H_
+#define _TALON_PROCESS_H_
+
+#include <sys/types.h>
+#include "buffer.h"
+
+typedef pid_t proc_handle;
+
+#define PROC_NORMALDEATH 0
+#define PROC_TIMEOUTDEATH 1
+#define PROC_SOMEODDDEATH 2
+#define PROC_PIPECREATE 3
+#define PROC_START 4
+
+
+typedef struct 
+{
+	proc_handle pid;
+	unsigned int starttime;
+	unsigned int endtime;
+	int returncode;
+	unsigned int causeofdeath;
+	buffer *output;
+} proc;
+
+proc *process_run(char executable[], char *args[], int timeout);
+void process_free(proc **pp);
+	
+#endif
--- a/sbsv2/raptor/util/talon/talonctl.c	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/talonctl.c	Wed Jun 23 16:56:47 2010 +0800
@@ -1,61 +1,61 @@
-/*
-* 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: 
-*
-*/
-
-
-
-
-#include "sema.h"
-#include "log.h"
-
-#include <stdlib.h>
-
-/* The output semaphore. */
-sbs_semaphore talon_sem;
-
-int main(int argc, char *argv[])
-{
-	char *buildid_str = getenv("TALON_BUILDID");
-
-	if (!buildid_str)
-	{
-		error("error: TALON_BUILDID not set in environment\n");
-		return 1;
-	}
-
-	if (argc != 2)
-	{
-		error("error: one argument required: start|stop\n");
-		return 1;
-	}
-
-	talon_sem.name = buildid_str;
-	talon_sem.timeout=0;
-
-	if (strcasecmp("start", argv[1]) == 0)
-	{
-		sema_create(&talon_sem);
-	}
-	else if (strcasecmp("stop", argv[1]) == 0)
-	{
-		sema_destroy(&talon_sem);
-	} else {
-		error("error: argument must be: start|stop\n");
-		return 1;
-	}
-
-	return 0;
-}
+/*
+* 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: 
+*
+*/
+
+
+
+
+#include "sema.h"
+#include "log.h"
+
+#include <stdlib.h>
+
+/* The output semaphore. */
+sbs_semaphore talon_sem;
+
+int main(int argc, char *argv[])
+{
+	char *buildid_str = getenv("TALON_BUILDID");
+
+	if (!buildid_str)
+	{
+		error("error: TALON_BUILDID not set in environment\n");
+		return 1;
+	}
+
+	if (argc != 2)
+	{
+		error("error: one argument required: start|stop\n");
+		return 1;
+	}
+
+	talon_sem.name = buildid_str;
+	talon_sem.timeout=0;
+
+	if (strcasecmp("start", argv[1]) == 0)
+	{
+		sema_create(&talon_sem);
+	}
+	else if (strcasecmp("stop", argv[1]) == 0)
+	{
+		sema_destroy(&talon_sem);
+	} else {
+		error("error: argument must be: start|stop\n");
+		return 1;
+	}
+
+	return 0;
+}
--- a/sbsv2/raptor/util/talon/testbuffer.c	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/testbuffer.c	Wed Jun 23 16:56:47 2010 +0800
@@ -1,77 +1,80 @@
-/*
-* 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: 
-*
-*/
-
-
-
-
-#include <stdio.h>
-#include <string.h>
-#include "buffer.h"
-#include <unistd.h>
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-
-#define OSIZE 40
-#define ISIZEMAX 2049
-
-int main(int argc, char *argv[])
-{
-	int nbytes = 0;
-	byteblock *bb=NULL;
-	buffer *b;
-	char *pointertospace = NULL;
-	int iterator = 0;
-	int ofile;
-	unsigned int space=51;
-
-	b = buffer_new();
-
-	do {
-// space %= 5;
-//		space++;
-		pointertospace = buffer_makespace(b, space);
-		if (!pointertospace)
-			exit(1);
-
-		nbytes = read(STDIN_FILENO, pointertospace, space);
-		if (nbytes == -1)
-			break;
-
-		buffer_usespace(b, nbytes);
-	}
-	while (nbytes == space);
-
-	iterator = 0;
-	ofile = open("/tmp/outfile", O_CREAT | O_WRONLY, 00777);
-
-	if (ofile <= 0)
-	{
-		perror("error");
-		return 1;
-	}
-	
-	while ((bb = buffer_getbytes(b, &iterator)))
-	{
-		write(ofile, &bb->byte0, bb->fill);
-	}
-	close(ofile);
-
-	buffer_free(&b);
-	return 0;
-}
+/*
+* Copyright (c) 2009-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 program reads from stdin into a "buffer" structure. It is designed to be
+* run from within valgrind to detect memory corruption errors.
+* The buffer is then written to /tmp/outfile where it can be compared
+* with the input to determine if they are the same
+*/
+
+
+
+
+#include <stdio.h>
+#include <string.h>
+#include "buffer.h"
+#include <unistd.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+
+#define OSIZE 40
+#define ISIZEMAX 2049
+
+int main(int argc, char *argv[])
+{
+	int nbytes = 0;
+	byteblock *bb=NULL;
+	buffer *b;
+	char *pointertospace = NULL;
+	int iterator = 0;
+	int ofile;
+	unsigned int space=51;
+
+	b = buffer_new();
+
+	do {
+// space %= 5;
+//		space++;
+		pointertospace = buffer_makespace(b, space);
+		if (!pointertospace)
+			exit(1);
+
+		nbytes = read(STDIN_FILENO, pointertospace, space);
+		if (nbytes == -1)
+			break;
+
+		buffer_usespace(b, nbytes);
+	}
+	while (nbytes == space);
+
+	iterator = 0;
+	ofile = open("/tmp/outfile", O_CREAT | O_WRONLY, 00777);
+
+	if (ofile <= 0)
+	{
+		perror("error");
+		return 1;
+	}
+	
+	while ((bb = buffer_getbytes(b, &iterator)))
+	{
+		write(ofile, &bb->byte0, bb->fill);
+	}
+	close(ofile);
+
+	buffer_free(&b);
+	return 0;
+}
--- a/sbsv2/raptor/util/talon/testprocess.c	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/testprocess.c	Wed Jun 23 16:56:47 2010 +0800
@@ -1,76 +1,80 @@
-/*
-* 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: 
-*
-*/
-
-
-
-
-#include <stdlib.h>
-#include <unistd.h>
-#include <stdio.h>
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-
-
-#include "process.h"
-
-int main(int argc, char *argv[])
-{
-	char *shell = getenv("TALON_SHELL");
-	char **args = malloc((argc+2)*sizeof(char *));
-	int i;
-	proc *p;
-
-	for (i=1; i < argc; i++)
-	{
-		args[i] = argv[i];
-		printf("arg: %s\n", args[i]);
-	}
-	args[argc] = NULL;
-
-	if (! shell)
-	{
-		fprintf(stderr, "error: %s", "TALONSHELL not set in environment\n");
-		return 1;
-	}
-
-	args[0]  = shell;
-	p = process_run(shell, args, 4000);
-
-	if (p) 
-	{
-
-		buffer_prepend(p->output, "<recipe>\n<!CDATA<[[\n", 20);
-		buffer_append(p->output, "\n]]></recipe>\n", 13);
-
-		unsigned int iterator = 0;
-		byteblock *bb;
-		while ((bb = buffer_getbytes(p->output, &iterator)))
-		{
-			write(STDOUT_FILENO, &bb->byte0, bb->fill);
-		}
-
-		process_free(&p);
-	} else {
-		fprintf(stderr, "error: %s", "failed to run process\n");
-		return 1;
-	}
-
-	free(args);
-	return 0;
-}
+/*
+* Copyright (c) 2009-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 programs tests the process execution functions in talon.
+* it executes it's first argument with the following arguments 
+* as parameters to it.  Output is buffered and finally printed.
+* Should be run from within valgrind if possible to detect memory
+* corruption errors.
+*/
+
+
+
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdio.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+
+
+#include "process.h"
+
+int main(int argc, char *argv[])
+{
+	char *shell = getenv("TALON_SHELL");
+	char **args = malloc((argc+2)*sizeof(char *));
+	int i;
+	proc *p;
+
+	for (i=1; i < argc; i++)
+	{
+		args[i] = argv[i];
+		printf("arg: %s\n", args[i]);
+	}
+	args[argc] = NULL;
+
+	if (! shell)
+	{
+		fprintf(stderr, "error: %s", "TALONSHELL not set in environment\n");
+		return 1;
+	}
+
+	args[0]  = shell;
+	p = process_run(shell, args, 4000);
+
+	if (p) 
+	{
+
+		buffer_prepend(p->output, "<recipe>\n<!CDATA<[[\n", 20);
+		buffer_append(p->output, "\n]]></recipe>\n", 13);
+
+		unsigned int iterator = 0;
+		byteblock *bb;
+		while ((bb = buffer_getbytes(p->output, &iterator)))
+		{
+			write(STDOUT_FILENO, &bb->byte0, bb->fill);
+		}
+
+		process_free(&p);
+	} else {
+		fprintf(stderr, "error: %s", "failed to run process\n");
+		return 1;
+	}
+
+	free(args);
+	return 0;
+}
--- a/sbsv2/raptor/util/talon/tests/old_taggedrules.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/tests/old_taggedrules.mk	Wed Jun 23 16:56:47 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: 
-# taggedrules.mk
-# Tools for use in FLMs - enabling the output from
-# rules to be logged with start and end tags.
-# This is a place where one might to permit various information to
-# be logged, such as timestamps and host names or process ids
-#
-
-ifndef _TAGGEDRULES_FLM_
-_TAGGEDRULES_FLM_:=1
-
-# only run recipes once by default
-RECIPETRIES?=1
-
-##
-##  Example usage:
-##
-#   define func
-#	auto_ok:
-#		$(call startrule,auto) \
-#		true && \
-#		true && \
-#		true    \
-#		$(call endrule,auto)
-#	
-#	auto_fail:
-#		$(call startrule,auto) \
-#		find /usr >/dev/null 2>&1 && \
-#		false && \
-#		true    \
-#		$(call endrule,auto)
-#   endef
-#   $(eval $(func))
-
-# $(1) is the name of the FLM function
-# $(2) indicates whether the failure of this rule should be ignored (but still logged)
-#      FORCESUCCESS indicates "on"
-define startrule
-  @set -o pipefail; RV=0; ATTEMPT=1; \
-  while (( $$$$ATTEMPT <= $(RECIPETRIES) )); do \
-    echo -e "<recipe name='$(1)' \
-    target='$$@' host='$$$$HOSTNAME' \
-    layer='$(COMPONENT_LAYER)' component='$(COMPONENT_NAME)' \
-    bldinf='$(COMPONENT_META)' mmp='$(PROJECT_META)' \
-    config='$(SBS_CONFIGURATION)' platform='$(PLATFORM)' \
-    phase='$(MAKEFILE_GROUP)' \
-    source='$(3)'>\n<![CDATA["; \
-    FLM_FORCESUCCESS=$(2); \
-    export TIMEFORMAT="]]><time start='$$$$($(DATE) +%s.%N)' elapsed='%6R' />"; \
-    { time { set -x;
-endef
-
-define endrule
-    ; }  } 2>&1  ; RV=$$$$?; set +x; \
-    if (( $$$$RV==0  )); then \
-       echo "<status exit='ok' attempt='$$$$ATTEMPT' />";  \
-       echo "</recipe>"; \
-       break; \
-    else  \
-       if (( $$$$ATTEMPT < $(RECIPETRIES) )); then \
-         echo "<status exit='retry' code='$$$$RV' attempt='$$$$ATTEMPT' />"; \
-         sleep 1; \
-       else \
-         if [ "$$$$FLM_FORCESUCCESS" == "FORCESUCCESS" ]; then \
-             echo "<status exit='failed' code='$$$$RV' attempt='$$$$ATTEMPT' forcesuccess='FORCESUCCESS' />"; \
-             RV=0; \
-         else \
-             echo "<status exit='failed' code='$$$$RV' attempt='$$$$ATTEMPT' />"; \
-         fi; \
-       fi; \
-    fi; \
-    echo "</recipe>"; \
-    (( ATTEMPT=$$$$ATTEMPT + 1 )); \
-  done $(if $(DESCRAMBLE),2>&1 | $(DESCRAMBLE) -k $$$$$$$$); exit $$$$RV 
-endef
-
-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: 
+# taggedrules.mk
+# Tools for use in FLMs - enabling the output from
+# rules to be logged with start and end tags.
+# This is a place where one might to permit various information to
+# be logged, such as timestamps and host names or process ids
+#
+
+ifndef _TAGGEDRULES_FLM_
+_TAGGEDRULES_FLM_:=1
+
+# only run recipes once by default
+RECIPETRIES?=1
+
+##
+##  Example usage:
+##
+#   define func
+#	auto_ok:
+#		$(call startrule,auto) \
+#		true && \
+#		true && \
+#		true    \
+#		$(call endrule,auto)
+#	
+#	auto_fail:
+#		$(call startrule,auto) \
+#		find /usr >/dev/null 2>&1 && \
+#		false && \
+#		true    \
+#		$(call endrule,auto)
+#   endef
+#   $(eval $(func))
+
+# $(1) is the name of the FLM function
+# $(2) indicates whether the failure of this rule should be ignored (but still logged)
+#      FORCESUCCESS indicates "on"
+define startrule
+  @set -o pipefail; RV=0; ATTEMPT=1; \
+  while (( $$$$ATTEMPT <= $(RECIPETRIES) )); do \
+    echo -e "<recipe name='$(1)' \
+    target='$$@' host='$$$$HOSTNAME' \
+    layer='$(COMPONENT_LAYER)' component='$(COMPONENT_NAME)' \
+    bldinf='$(COMPONENT_META)' mmp='$(PROJECT_META)' \
+    config='$(SBS_CONFIGURATION)' platform='$(PLATFORM)' \
+    phase='$(MAKEFILE_GROUP)' \
+    source='$(3)'>\n<![CDATA["; \
+    FLM_FORCESUCCESS=$(2); \
+    export TIMEFORMAT="]]><time start='$$$$($(DATE) +%s.%N)' elapsed='%6R' />"; \
+    { time { set -x;
+endef
+
+define endrule
+    ; }  } 2>&1  ; RV=$$$$?; set +x; \
+    if (( $$$$RV==0  )); then \
+       echo "<status exit='ok' attempt='$$$$ATTEMPT' />";  \
+       echo "</recipe>"; \
+       break; \
+    else  \
+       if (( $$$$ATTEMPT < $(RECIPETRIES) )); then \
+         echo "<status exit='retry' code='$$$$RV' attempt='$$$$ATTEMPT' />"; \
+         sleep 1; \
+       else \
+         if [ "$$$$FLM_FORCESUCCESS" == "FORCESUCCESS" ]; then \
+             echo "<status exit='failed' code='$$$$RV' attempt='$$$$ATTEMPT' forcesuccess='FORCESUCCESS' />"; \
+             RV=0; \
+         else \
+             echo "<status exit='failed' code='$$$$RV' attempt='$$$$ATTEMPT' />"; \
+         fi; \
+       fi; \
+    fi; \
+    echo "</recipe>"; \
+    (( ATTEMPT=$$$$ATTEMPT + 1 )); \
+  done $(if $(DESCRAMBLE),2>&1 | $(DESCRAMBLE) -k $$$$$$$$); exit $$$$RV 
+endef
+
+endif
--- a/sbsv2/raptor/util/talon/tests/t.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/tests/t.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,41 +1,42 @@
-#
-# 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: 
-#
-
-
-HOSTNAME:=fred
-COMPONENT_LAYER:=base
-COMPONENT:=compsupp
-COMPONENT_META:=compsupp.inf
-PROJECT_META:=simpledll
-SBS_CONFIGURATION:=armv5.fred
-PLATFORM:=armv5
-MAKEFILE_GROUP:=phasenone
-FLM_FORCESUCCESS:=FORCESUCCESS
-
-#HOSTNAME:=fred; COMPONENT_LAYER:=base; COMPONENT:=compsupp; COMPONENT_META:=compsupp.inf; PROJECT_META:=simpledll; SBS_CONFIGURATION:=armv5.fred; PLATFORM:=armv5; MAKEFILE_GROUP:=phasenone; FLM_FORCESUCCESS:=FORCESUCCESS
-
-
-TALON_RECIPEATTRIBUTES:="target='$$@' host='$$$$HOSTNAME' layer='$(COMPONENT_LAYER)' component='$(COMPONENT_NAME)' bldinf='$(COMPONENT_META)' mmp='$(PROJECT_META)' config='$(SBS_CONFIGURATION)' platform='$(PLATFORM)' phase='$(MAKEFILE_GROUP)' FLM_FORCESUCCESS=$(FLM_FORCESUCCESS)"
-
-.PHONY: target
-	
-define flm
-target:
-	HOSTNAME:=fred; COMPONENT_LAYER:=base; COMPONENT:=compsupp; COMPONENT_META:=compsupp.inf; PROJECT_META:=simpledll; SBS_CONFIGURATION:=armv5.fred; PLATFORM:=armv5; MAKEFILE_GROUP:=phasenone; FLM_FORCESUCCESS:=FORCESUCCESS ; echo "<recipe $(TALON_RECIPEATTRIBUTES) >"; echo;
-endef
-
-
-$(eval $(flm))
+#
+# 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: 
+#
+
+include settings.mk
+
+HOSTNAME:=fred
+COMPONENT_LAYER:=base
+COMPONENT:=compsupp
+COMPONENT_META:=compsupp.inf
+PROJECT_META:=simpledll
+SBS_CONFIGURATION:=armv5.fred
+PLATFORM:=armv5
+MAKEFILE_GROUP:=phasenone
+FLM_FORCESUCCESS:=FORCESUCCESS
+
+#HOSTNAME:=fred; COMPONENT_LAYER:=base; COMPONENT:=compsupp; COMPONENT_META:=compsupp.inf; PROJECT_META:=simpledll; SBS_CONFIGURATION:=armv5.fred; PLATFORM:=armv5; MAKEFILE_GROUP:=phasenone; FLM_FORCESUCCESS:=FORCESUCCESS
+
+
+TALON_RECIPEATTRIBUTES:="target='$$@' host='$$$$HOSTNAME' layer='$(COMPONENT_LAYER)' component='$(COMPONENT_NAME)' bldinf='$(COMPONENT_META)' mmp='$(PROJECT_META)' config='$(SBS_CONFIGURATION)' platform='$(PLATFORM)' phase='$(MAKEFILE_GROUP)' FLM_FORCESUCCESS=$(FLM_FORCESUCCESS)"
+
+.PHONY: target
+	
+define flm
+target:
+	HOSTNAME:=fred; COMPONENT_LAYER:=base; COMPONENT:=compsupp; COMPONENT_META:=compsupp.inf; PROJECT_META:=simpledll; SBS_CONFIGURATION:=armv5.fred; PLATFORM:=armv5; MAKEFILE_GROUP:=phasenone; FLM_FORCESUCCESS:=FORCESUCCESS ; echo "<recipe $(TALON_RECIPEATTRIBUTES) >"; echo;
+endef
+
+
+$(eval $(flm))
--- a/sbsv2/raptor/util/talon/tests/t2.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/tests/t2.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,32 +1,32 @@
-#
-# 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: 
-#
-
-all: a b
-
-define doa
-a:
-	x
-endef
-
-define dob
-b:
-	y
-endef
-
-SHELL:=bash -c echo ho
-$(eval $(doa))
-SHELL:=bash -c echo hi
-$(eval $(dob))
+#
+# 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: 
+#
+
+all: a b
+
+define doa
+a:
+	x
+endef
+
+define dob
+b:
+	y
+endef
+
+SHELL:=bash -c echo ho
+$(eval $(doa))
+SHELL:=bash -c echo hi
+$(eval $(dob))
--- a/sbsv2/raptor/util/talon/tests/t3.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/tests/t3.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,37 +1,37 @@
-#
-# 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: 
-#
-
-SHELL:=$(TALON)
-TALON_RECIPEATTRIBUTES:=name='$$RECIPENAME' host='$$HOSTNAME'
-export TALON_RECIPEATTRIBUTES
-
-
-$(info SHELL="$(SHELL)")
-
-# using an override doesn't i.e. "make SHELL:=xxxx" fails on windows at least.
-# so one can try "make TALON:=xxxx" and in the makefile one must set SHELL=$(TALON)
-
-all: hello world
-
-hello:
-	@echo "some output" 
-	@|RECIPENAME=hello;|echo "The recipe name is $$RECIPENAME"
-
-
-world:
-	@echo "more output" 
-	@|RECIPENAME=world;|echo "The recipe name is $$RECIPENAME"
-
+#
+# Copyright (c) 2009-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 settings.mk
+
+TALON_RECIPEATTRIBUTES:=name='$$RECIPENAME' host='$$HOSTNAME'
+export TALON_RECIPEATTRIBUTES 
+
+
+$(info SHELL="$(SHELL)")
+
+# using an override doesn't i.e. "make SHELL:=xxxx" fails on windows at least.
+# so one can try "make TALON:=xxxx" and in the makefile one must set SHELL=$(TALON)
+
+all: hello world
+
+hello:
+	@echo "some output" 
+	@|RECIPENAME=hello;|echo "The recipe name is $$RECIPENAME"
+
+
+world:
+	@echo "more output" 
+	@|RECIPENAME=world;|echo "The recipe name is $$RECIPENAME"
+
--- a/sbsv2/raptor/util/talon/tests/t4.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/tests/t4.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,28 +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: 
-#
-
-SHELL:=$(TALON)
-TALON_TIMEOUT:=4000
-TALON_RETRIES:=4
-TALON_RECIPEATTRIBUTES:=platform='$$PLATFORM' mmp='$$MMP' bldinf='$$BLDINF'
-export 
-
-$(info testing timeouts)
-$(info )
-
-all:
-	@|PLATFORM=armv5;MMP=barney.mmp;BLDINF=somebld.inf;|echo "Started a slow command under talon (attempt $$TALON_ATTEMPT):";echo "SHELL=$$SHELL";if (( $$TALON_ATTEMPT <4 )); then echo sleeping 6; sleep 6; echo "hi"; else echo "Not sleeping this time"; fi; echo "this should not appear in the recipe tags unless you try 4 times."
-
+#
+# Copyright (c) 2009-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 settings.mk
+TALON_TIMEOUT:=4000
+TALON_RETRIES:=4
+TALON_RECIPEATTRIBUTES:=platform='$$PLATFORM' mmp='$$MMP' bldinf='$$BLDINF'
+export 
+
+$(info testing timeouts)
+$(info )
+
+.PHONY: all passed
+
+all: passed
+	@echo "t4-PASSED"
+
+passed:
+	@|PLATFORM=armv5;MMP=barney.mmp;BLDINF=somebld.inf;|echo "Started a slow command under talon (attempt $$TALON_ATTEMPT):";echo "SHELL=$$SHELL";if (( $$TALON_ATTEMPT <4 )); then echo sleeping 6; sleep 6; echo "hi"; else echo "Not sleeping this time"; fi; echo "this should not appear in the recipe tags unless you try 4 times."
+
--- a/sbsv2/raptor/util/talon/tests/t5.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/tests/t5.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,18 +1,19 @@
-#
-# 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: 
-#
-
-all:
-	||"echo this command should cause a bash error which should be visible"
+#
+# Copyright (c) 2009-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 settings.mk
+
+all:
+	||"echo this command should cause a bash error which should be visible"
--- a/sbsv2/raptor/util/talon/tests/taggedrules.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/tests/taggedrules.mk	Wed Jun 23 16:56:47 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: 
-# Tools for use in FLMs - enabling the output from
-# rules to be logged with start and end tags.
-# This is a place where one might to permit various information to
-# be logged, such as timestamps and host names or process ids
-#
-
-ifndef _TAGGEDRULES_FLM_
-_TAGGEDRULES_FLM_:=1
-
-
-TALON_RECIPEATTRIBUTES:=\
- name='$$RECIPE'\
- target='$$TARGET'\
- host='$$HOSTNAME'\
- layer='$$COMPONENT_LAYER'\
- component='$$COMPONENT_NAME'\
- bldinf='$$COMPONENT_META' mmp='$$PROJECT_META'\
- config='$$SBS_CONFIGURATION' platform='$$PLATFORM'\
- phase='$$MAKEFILE_GROUP'
-
-export TALON_RECIPEATTRIBUTES
-
-# only run recipes once by default
-RECIPETRIES?=1
-TALON_RETRIES:=$(RECIPETRIES)
-export TALON_RECIPEATTRIBUTES
-
-define startrule
-	@|RECIPE=$1;TARGET=$@;COMPONENT_LAYER=$(COMPONENT_LAYER);COMPONENT_NAME=$(COMPONENT_NAME);COMPONENT_META=$(COMPONENT_META);PROJECT_META=$(PROJECT_META);SBS_CONFIGURATION=$(SBS_CONFIGURATION);PLATFORM=$(PLATFORM);MAKEFILE_GROUP=$(MAKEFILE_GROUP);|
-endef
-
-define endrule
-endef
-
-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: 
+# Tools for use in FLMs - enabling the output from
+# rules to be logged with start and end tags.
+# This is a place where one might to permit various information to
+# be logged, such as timestamps and host names or process ids
+#
+
+ifndef _TAGGEDRULES_FLM_
+_TAGGEDRULES_FLM_:=1
+
+
+TALON_RECIPEATTRIBUTES:=\
+ name='$$RECIPE'\
+ target='$$TARGET'\
+ host='$$HOSTNAME'\
+ layer='$$COMPONENT_LAYER'\
+ component='$$COMPONENT_NAME'\
+ bldinf='$$COMPONENT_META' mmp='$$PROJECT_META'\
+ config='$$SBS_CONFIGURATION' platform='$$PLATFORM'\
+ phase='$$MAKEFILE_GROUP'
+
+export TALON_RECIPEATTRIBUTES
+
+# only run recipes once by default
+RECIPETRIES?=1
+TALON_RETRIES:=$(RECIPETRIES)
+export TALON_RECIPEATTRIBUTES
+
+define startrule
+	@|RECIPE=$1;TARGET=$@;COMPONENT_LAYER=$(COMPONENT_LAYER);COMPONENT_NAME=$(COMPONENT_NAME);COMPONENT_META=$(COMPONENT_META);PROJECT_META=$(PROJECT_META);SBS_CONFIGURATION=$(SBS_CONFIGURATION);PLATFORM=$(PLATFORM);MAKEFILE_GROUP=$(MAKEFILE_GROUP);|
+endef
+
+define endrule
+endef
+
+endif
--- a/sbsv2/raptor/util/talon/tests/xcopystdin.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/talon/tests/xcopystdin.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,26 +1,24 @@
-#
-# 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: 
-#
-
-SHELL:=$(SBS_HOME)/win32/bin/talon.exe
-TALON_SHELL:=$(SBS_HOME)/win32/cygwin/bin/bash.exe
-TALON_BUILDID:=1
-TALON_RECIPEATTRIBUTES:=123
-
-export
-
-all::
-	@|name=fred;|mkdir out;touch source.txt;xcopy /y source.txt out
-
+#
+# Copyright (c) 2009-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 settings.mk
+TALON_RECIPEATTRIBUTES:=123
+
+export
+
+all::
+	@|name=fred;|mkdir out;touch source.txt;xcopy /y source.txt out
+
--- a/sbsv2/raptor/util/utilbuild.mk	Wed Jun 16 16:51:40 2010 +0300
+++ b/sbsv2/raptor/util/utilbuild.mk	Wed Jun 23 16:56:47 2010 +0800
@@ -1,50 +1,50 @@
-#
-# 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: 
-# Utility makefile 
-#
-
-CHAR_BLANK:=
-CHAR_SPACE:=$(CHAR_BLANK) $(CHAR_BLANK)
-
-HOSTPLATFORM:=$(shell $(SBS_HOME)/bin/gethost.sh)
-HOSTPLATFORM_DIR:=$(shell $(SBS_HOME)/bin/gethost.sh -d)
-
-ifeq ($(filter $(HOSTPLATFORM),win),win)
-PROGRAMEXT:=.exe
-HOSTMACROS:=-DHOST_WIN -DHOST_DIR=$(HOSTPLATFORM_DIR)
-else
-PROGRAMEXT:=
-HOSTMACROS:=-DHOST_LINUX -DHOST_DIR=$(HOSTPLATFORM_DIR)
-endif
-
-GCCTUNE:=
-ifeq ($(filter $(HOSTPLATFORM),x86_64),x86_64)
-else
-GCCTUNE:=-mtune=i686
-endif
-
-BUILDDIR:=$(subst \,/,$(SBS_HOME))/util/build
-INSTALLROOT:=$(subst \,/,$(SBS_HOME))/$(HOSTPLATFORM_DIR)
-BINDIR:=$(INSTALLROOT)/bin
-OUTPUTPATH:=$(BUILDDIR)/$(HOSTPLATFORM_DIR)
-
-define cleanlog
-ifneq ($(CLEANMODE),)
-$$(info <clean>)
-$$(foreach O,$$(CLEANFILES),$$(info <file>$$(O)</file>)) 
-$$(info </clean>)
-endif
-endef
-
+#
+# 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: 
+# Utility makefile 
+#
+
+CHAR_BLANK:=
+CHAR_SPACE:=$(CHAR_BLANK) $(CHAR_BLANK)
+
+HOSTPLATFORM:=$(shell $(SBS_HOME)/bin/gethost.sh)
+HOSTPLATFORM_DIR:=$(shell $(SBS_HOME)/bin/gethost.sh -d)
+
+ifeq ($(filter $(HOSTPLATFORM),win),win)
+PROGRAMEXT:=.exe
+HOSTMACROS:=-DHOST_WIN -DHOST_DIR=$(HOSTPLATFORM_DIR)
+else
+PROGRAMEXT:=
+HOSTMACROS:=-DHOST_LINUX -DHOST_DIR=$(HOSTPLATFORM_DIR)
+endif
+
+GCCTUNE:=
+ifeq ($(filter $(HOSTPLATFORM),x86_64),x86_64)
+else
+GCCTUNE:=-mtune=i686
+endif
+
+BUILDDIR:=$(subst \,/,$(SBS_HOME))/util/build
+INSTALLROOT:=$(subst \,/,$(SBS_HOME))/$(HOSTPLATFORM_DIR)
+BINDIR:=$(INSTALLROOT)/bin
+OUTPUTPATH:=$(BUILDDIR)/$(HOSTPLATFORM_DIR)
+
+define cleanlog
+ifneq ($(CLEANMODE),)
+$$(info <clean>)
+$$(foreach O,$$(CLEANFILES),$$(info <file>$$(O)</file>)) 
+$$(info </clean>)
+endif
+endef
+
Binary file sbsv2/raptor/win32/bin/ransleep.exe has changed
Binary file sbsv2/raptor/win32/bin/talon.exe has changed
Binary file sbsv2/raptor/win32/bin/talonctl.exe has changed
--- a/srctools/tranasm/group/bld.inf	Wed Jun 16 16:51:40 2010 +0300
+++ b/srctools/tranasm/group/bld.inf	Wed Jun 23 16:56:47 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	Wed Jun 16 16:51:40 2010 +0300
+++ b/srctools/tranasm/group/tranasm.mrp	Wed Jun 23 16:56:47 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